package com.mingqijia.gassafety.webserver.service.impl;

import static com.mingqijia.gassafety.shared.constant.Constants.BIND_CHANNEL_ASST;
import static com.mingqijia.gassafety.shared.constant.Constants.COMMUNICATION_Mode_CODE;
import static com.mingqijia.gassafety.shared.constant.Constants.DETECTION_TYPE_CODE;
import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;
import static com.mingqijia.gassafety.shared.constant.Constants.OPERATE_RESULT_FAIL;
import static com.mingqijia.gassafety.shared.constant.Constants.OPERATE_RESULT_SUCCESS_PART;
import static com.mingqijia.gassafety.shared.constant.Constants.OPERATOR_CODE;
import static com.mingqijia.gassafety.shared.constant.TableConst.dtu;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import javax.validation.Valid;

import com.mingqijia.gassafety.db.entity.vo.EquipmentListParamVO;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.inner.*;
import com.mingqijia.gassafety.webserver.response.baidu.BaiDuDetailResp;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkUserListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.utils.CoordinatesTransitionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.BusinessNotice;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.ConsumerDtuHistory;
import com.mingqijia.gassafety.db.entity.ConsumerServiceInfo;
import com.mingqijia.gassafety.db.entity.DeviceState;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.Dtu;
import com.mingqijia.gassafety.db.entity.DtuAep;
import com.mingqijia.gassafety.db.entity.DtuBindingOrder;
import com.mingqijia.gassafety.db.entity.FieldTemplate;
import com.mingqijia.gassafety.db.entity.FileUpload;
import com.mingqijia.gassafety.db.entity.Idmap;
import com.mingqijia.gassafety.db.entity.ReceiverValve;
import com.mingqijia.gassafety.db.entity.RecordController;
import com.mingqijia.gassafety.db.entity.RecordDetector;
import com.mingqijia.gassafety.db.entity.RunningStrategyReport;
import com.mingqijia.gassafety.db.entity.WorkOrderHistory;
import com.mingqijia.gassafety.db.entity.redis.LatestLog;
import com.mingqijia.gassafety.db.entity.vo.DeviceStateVO;
import com.mingqijia.gassafety.db.entity.vo.OperationLogVO;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.mapper.ConsumerDtuHistoryMapper;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.ConsumerServiceInfoMapper;
import com.mingqijia.gassafety.db.mapper.DeviceStateMapper;
import com.mingqijia.gassafety.db.mapper.DictionaryMapper;
import com.mingqijia.gassafety.db.mapper.DtuAepMapper;
import com.mingqijia.gassafety.db.mapper.DtuBindingOrderMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.FileUploadMapper;
import com.mingqijia.gassafety.db.mapper.JvInfoMapper;
import com.mingqijia.gassafety.db.mapper.ReceiverValveMapper;
import com.mingqijia.gassafety.db.mapper.RecordControllerMapper;
import com.mingqijia.gassafety.db.mapper.RecordDetectorMapper;
import com.mingqijia.gassafety.db.mapper.RunningStrategyReportMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.ConsumerServiceStatusEnum;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.constant.MbpConst;
import com.mingqijia.gassafety.shared.constant.OperateRecordEnum;
import com.mingqijia.gassafety.shared.constant.OperationTypeEnum;
import com.mingqijia.gassafety.shared.constant.PageColumnConst;
import com.mingqijia.gassafety.shared.constant.PageListCode;
import com.mingqijia.gassafety.shared.constant.SignalEnum;
import com.mingqijia.gassafety.shared.constant.TableConst;
import com.mingqijia.gassafety.shared.constant.ValveStatusEnum;
import com.mingqijia.gassafety.shared.dto.LogVO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.CompareUtil;
import com.mingqijia.gassafety.shared.utils.EntityUtils;
import com.mingqijia.gassafety.shared.utils.FileUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.constant.DeviceConstant;
import com.mingqijia.gassafety.webserver.request.ComsumerEquipmentRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerBindingHistoryRequest;
import com.mingqijia.gassafety.webserver.request.ConsumerDtuHistoryRequest;
import com.mingqijia.gassafety.webserver.request.DetectorRequest;
import com.mingqijia.gassafety.webserver.request.EditDeviceRequest;
import com.mingqijia.gassafety.webserver.request.EquipmentAddressRequest;
import com.mingqijia.gassafety.webserver.request.EquipmentListRequest;
import com.mingqijia.gassafety.webserver.request.EquipmentPositionRequest;
import com.mingqijia.gassafety.webserver.request.LatestLogListRequest;
import com.mingqijia.gassafety.webserver.request.SaveDeviceRequest;
import com.mingqijia.gassafety.webserver.request.client.ClientDtuListRequest;
import com.mingqijia.gassafety.webserver.response.ConsumerBindingHistoryResponse;
import com.mingqijia.gassafety.webserver.response.ConsumerDtuHistoryResponse;
import com.mingqijia.gassafety.webserver.response.ConsumerEquipmentResponse;
import com.mingqijia.gassafety.webserver.response.ConsumerStatusResponse;
import com.mingqijia.gassafety.webserver.response.DtuInfoResponse;
import com.mingqijia.gassafety.webserver.response.DtuListResponse;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.response.OrderInfoResponse;
import com.mingqijia.gassafety.webserver.response.ReceiverValveResponse;
import com.mingqijia.gassafety.webserver.response.client.DtuResponse;
import com.mingqijia.gassafety.webserver.response.inner.IotskDtuResponse;
import com.mingqijia.gassafety.webserver.response.workorder.asst.LoopInfoResponse;
import com.mingqijia.gassafety.webserver.service.aep.EquipmentAepService;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import com.mingqijia.gassafety.webserver.utils.LogRecordAspect;
import com.mingqijia.gassafety.webserver.utils.LogUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 控制器表 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-02-21
 */
@Service
@Slf4j
public class EquipmentServiceImpl extends ServiceImpl<DtuMapper, Dtu> implements EquipmentService {

    @Value("${gassafety.hangzhou.yhSpId}")
    private String hangzhouSpId;
    @Value("${baidu.maps.key}")
    private String baiDuMapsKey;
    @Autowired
    DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    DeviceStateService deviceStateService;
    @Autowired
    private DtuMapper dtuMapper;
    @Autowired
    LatestLogService latestLogService;
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private ConsumerMapper consumerMapper;
    @Autowired
    private DtuAepMapper dtuAepMapper;
    @Autowired
    private IdmapServiceImpl idmapService;
    @Autowired
    private EquipmentAepService equipmentAepService;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    InfluxDBConfiguration influxDBConnect;
    @Autowired
    RedisCache redisCache;
    @Autowired
    FileUploadMapper fileUploadMapper;
    @Autowired
    CustomerSubsHistoryService customerSubsHistoryService;
    @Autowired
    ConsumerDtuHistoryMapper consumerDtuHistoryMapper;
    @Autowired
    ConsumerServiceInfoMapper consumerServiceInfoMapper;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    EquipmentCmpService equipmentCmpService;
    @Autowired
    RecordControllerMapper recordControllerMapper;

    @Autowired
    RecordDetectorMapper recordDetectorMapper;
    @Autowired
    private OperationLogService operationLogService;
    @Autowired
    private CompareUtil compareUtil;
    @Autowired
    private JvInfoMapper jvInfoMapper;
    @Autowired
    private DeviceStateMapper deviceStateMapper;
    @Autowired
    private ReceiverValveMapper receiverValveMapper;
    @Autowired
    private RunningStrategyReportMapper reportMapper;
    @Autowired
    private CommonService commonService;
    public static final String format = "yyyy-MM-dd HH:mm:ss";
    public static final String yyMM = "yyMM";
    public static final String split = ";";
    public static final String split_ = "-";
    public static final String v1 = "v1.0";
    public static final String v2 = "v2.0";

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    ReceiverValveService receiverValveService;
    @Autowired
    WorkOrderHistoryService workOrderHistoryService;

    @Autowired
    FieldListShowService fieldListShowService;
    @Autowired
    FileUtil fileUtil;
    @Autowired
    ConsumerServiceInfoService consumerServiceInfoService;

    @Autowired
    BusinessNoticeService noticeService;
    @Autowired
    ConsoleSkFeignClient consoleSkFeignClient;

    @Autowired
    DictionaryService dictionaryService;

    private ExecutorService executor = Executors.newFixedThreadPool(10);
    /**
     * 新增设备
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDevice(SaveDeviceRequest request) {
        String formatDate = "";
        DateTime parse = null;
        if (DeviceConstant.WiFi_COMMUNICATIONMODE
                .equals(request.getCommunicationMode())) {
            throw new BizException("不支持这种通讯方式新增");
        }
        int validity = request.getValidity();
        if (validity < 0) throw new BizException("设备有效期为正整数");
        String protocolVersion = request.getProtocolVersion();
        String loopPoint = request.getLoopPoint();
        if (protocolVersion == null || (!protocolVersion.equals("v1.0") && !protocolVersion.equals("v2.0")))
            throw new BizException("输入协议版本有误");
        checkLoopPoint(loopPoint);
        String spId = ApplicationUtils.getWorkingSpId();
        //设备号是否唯一
        List<Dtu> dtus = checkIMEI(request.getImei());
        if ((!CollectionUtil.isEmpty(dtus) && dtus.get(0).getIsDeleted() == 0) || dtus.size() > 1
        )
            throw new BizException("设备号已存在");
        List<Dtu> ds = checkICCID(request.getIccid());
        if (!CollectionUtil.isEmpty(ds))
            throw new BizException("ICCID已经存在");
        //新增
        Dtu dtu = new Dtu();
        BeanUtils.copyProperties(request, dtu);
        dtu.setId(request.getImei());
        dtu.setIMEI(request.getImei());
        dtu.setParentImei(request.getImei());
        if (!EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(request.getEquipmentType())) {
            if (EquipmentType.HOME_GAS_DETECTOR.getCode()
                    .equals(request.getEquipmentType())) {
                dtu.setValidity(5);
            } else {
                dtu.setValidity(3);
            }
        }
        //按照设备第一次上报的时间计算到期时间
        Date reported = new Date();
        if (StringUtils.isEmpty(formatDate) || parse == null) {
            formatDate = DateUtil.format(reported, EquipmentServiceImpl.format);
            dtu.setNetInTime(formatDate);
        } else {
            dtu.setNetInTime(formatDate);
        }

        dtu.setSpId(spId);
        Map<String, Object> equipmentId = getEquipmentId(request.getEquipmentManufacturer()
                , request.getOperators(), request.getEquipmentType(), null,request.getImei());
        dtu.setDeviceCode(equipmentId.get("id") + "");
        dtu.setInstallTime(new Date());
        dtu.setCreateYM(Integer.parseInt(DateUtil.format(new Date(), yyMM)));
        dtu.setSerialNumber(equipmentId.get("serialNumber") + "");
        dtu.setIsDeleted(0);
        dtu.setSpId(spId);
        String path = dtuMapper.selectPath(spId);
        if (!StringUtils.isEmpty(path)) dtu.setPath(path);
        if (!StringUtils.isEmpty(dtu.getDetectionType()))
            dtu.setDetectionType(request.getDetectionType() + ";");
        if (EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equals(request.getEquipmentType())) {
            dtu.setRegisterTime(formatDate);
        } else {
            dtu.setRegisterTime(DateUtil.format(new Date(), EquipmentServiceImpl.format));
        }

        dtu.setCmpRegistered(1);
        if (!CollectionUtil.isEmpty(dtus)) {
            Dtu d = dtus.get(0);
            if (parse == null) {
                dtu.setNetInTime("");
            }
            UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(Dtu::getId, d.getId())
                    .eq(Dtu::getIMEI, request.getImei());
            dtu.setIMEI(d.getId());
            dtu.setConsumerId(0);
            dtu.setSectorType(Constants.BLANK);
            dtu.setExpirationTime("");
            dtuMapper.update(dtu, updateWrapper);
            cmpRegisterUpdate(dtu, 0, "NB".equals(dtu.getCommunicationMode())?0:1);
        } else {
            dtuMapper.insert(dtu);
            cmpRegisterUpdate(dtu, 0, "NB".equals(dtu.getCommunicationMode())?0:1);
        }

        //企业级操作日志
        LogVO vo = new LogVO();
        StringBuilder stringBuilder = new StringBuilder();
        String detail = LogUtil.addOrDeleteEntity(dtu, Dtu.class);
        stringBuilder.append(detail);
        if (!StringUtils.isEmpty(dtu.getLoopPoint())){
            stringBuilder.append("回路信息：");
            String[] split = dtu.getLoopPoint().split(";");
            for (int i = 0; i < split.length; i++) {
                stringBuilder.append("回路").append(i).append("：").append(split[i]).append("点位");
                if (i < split.length -1){
                    stringBuilder.append(",");
                }
            }
        }
        vo.setDetail(stringBuilder.toString());
        LogRecordAspect.threadLocal.set(vo);

        //操作日志log-24
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_24.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(dtu.getId());
        operationLogService.insertLog(logVO);

    }

    @Override
    @Transactional
    public Integer saveZJWifiDevice(ZJCreateBindRequest request) {
        Integer count = 0;
        String spId = request.getSpId();
        //设备号是否唯一
        List<Dtu> dtus = checkIMEI(request.getImei());
        if ((!CollectionUtil.isEmpty(dtus) && dtus.get(0).getIsDeleted() == 0) || dtus.size() > 1){
            throw new BizException("设备号已存在");
        }
        //新增
        Dtu dtu = new Dtu();
        dtu.setId(request.getImei());
        dtu.setIMEI(request.getImei());
        dtu.setParentImei(request.getImei());
        dtu.setEquipmentManufacturer(Constants.ZJ_EQUIPMENT_MANUFACTURER);
        dtu.setEquipmentType(EquipmentType.HOME_GAS_DETECTOR.getCode());
        dtu.setEquipmentModel(Constants.ZJ_EQUIPMENT_MODEL);
        dtu.setDetectionType("CH₄;");
        dtu.setProtocolVersion("v2.0");
        dtu.setEquipmentFrom(Constants.ZJ_EQUIPMENT_FROM);
        dtu.setPositionLon(request.getPositionLon());
        dtu.setPositionLat(request.getPositionLat());
        dtu.setOnlineCode(request.getOnlineCode());
        dtu.setDeviceNo(Constants.ZJ_DEVICE_NO);
        dtu.setSpId(spId);
        dtu.setInstallTime(new Date());
        dtu.setCreateYM(Integer.parseInt(DateUtil.format(new Date(), yyMM)));
        dtu.setIsDeleted(0);
        dtu.setDeviceCode("");
        dtu.setInstallationAddress("");
        String path = dtuMapper.selectPath(spId);
        if (!StringUtils.isEmpty(path)) dtu.setPath(path);

        dtu.setNetInTime(dtu.getRegisterTime());
        dtu.setCmpRegistered(1);
        if (!CollectionUtil.isEmpty(dtus)) {
            Dtu d = dtus.get(0);
            UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(Dtu::getId, d.getId())
                    .eq(Dtu::getIMEI, request.getImei());
            dtu.setIMEI(d.getId());
            dtu.setConsumerId(0);
            dtu.setSectorType(Constants.BLANK);
            dtu.setExpirationTime("");
            count = dtuMapper.update(dtu, updateWrapper);
        } else {
            dtu.setRegisterTime(DateUtil.format(new Date(), EquipmentServiceImpl.format));
            count = dtuMapper.insert(dtu);
        }
        saveEquipment(dtu.getIMEI());
        //操作日志log-24
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_24.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(dtu.getId());
        logVO.setOperationPersonCode("智慧厨房");
        logVO.setOperationPersonName("smartKitchen");
        logVO.setSpId(spId);
        operationLogService.insertLog(logVO);
        return count;
    }

    @Override
    @Transactional
    public Integer saveUpdateZJWifiDevice(ZJCreateBindRequest request) {
        Integer count = 0;
        String spId = request.getSpId();
        //设备号是否唯一
        List<Dtu> dtus = checkIMEI(request.getImei());
        if ((!CollectionUtil.isEmpty(dtus) && dtus.get(0).getIsDeleted() == 0) || dtus.size() > 1){
            return dtus.size();
        }
        //新增
        Dtu dtu = new Dtu();
        dtu.setId(request.getImei());
        dtu.setIMEI(request.getImei());
        dtu.setParentImei(request.getImei());
        dtu.setEquipmentManufacturer(Constants.ZJ_EQUIPMENT_MANUFACTURER);
        dtu.setEquipmentType(EquipmentType.HOME_GAS_DETECTOR.getCode());
        dtu.setEquipmentModel(Constants.ZJ_EQUIPMENT_MODEL);
        dtu.setDetectionType("CH₄;");
        dtu.setProtocolVersion("v2.0");
        dtu.setEquipmentFrom(Constants.ZJ_EQUIPMENT_FROM);
        dtu.setPositionLon(request.getPositionLon());
        dtu.setPositionLat(request.getPositionLat());
        dtu.setOnlineCode(request.getOnlineCode());
        dtu.setDeviceNo(Constants.ZJ_DEVICE_NO);
        dtu.setSpId(spId);
        dtu.setInstallTime(new Date());
        dtu.setCreateYM(Integer.parseInt(DateUtil.format(new Date(), yyMM)));
        dtu.setIsDeleted(0);
        dtu.setDeviceCode("");
        dtu.setInstallationAddress("");
        String path = dtuMapper.selectPath(spId);
        if (!StringUtils.isEmpty(path)) dtu.setPath(path);

        dtu.setNetInTime(dtu.getRegisterTime());
        dtu.setCmpRegistered(1);
        if (!StringUtils.isEmpty(request.getDtuRemark())) {
            dtu.setRemark(request.getDtuRemark());
        }
        if (!CollectionUtil.isEmpty(dtus)) {
            Dtu d = dtus.get(0);
            UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(Dtu::getId, d.getId())
                    .eq(Dtu::getIMEI, request.getImei());
            dtu.setIMEI(d.getId());
            dtu.setConsumerId(0);
            dtu.setSectorType(Constants.BLANK);
            dtu.setExpirationTime("");
            count = dtuMapper.update(dtu, updateWrapper);
        } else {
            dtu.setRegisterTime(DateUtil.format(new Date(), EquipmentServiceImpl.format));
            count = dtuMapper.insert(dtu);
        }
        saveEquipment(dtu.getIMEI());
        //操作日志log-24
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_24.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(dtu.getId());
        logVO.setOperationPersonCode("智慧厨房");
        logVO.setOperationPersonName("smartKitchen");
        logVO.setSpId(spId);
        operationLogService.insertLog(logVO);

        // 添加接收器和电磁阀
        ReceiverValve receiverValve = new ReceiverValve();
        receiverValve.setReceiverCode(request.getReceiverCode());
        receiverValve.setDeviceId(request.getImei());
        receiverValve.setSpId(spId);
        receiverValveService.addReceiverValve(receiverValve);
        return count;
    }

    @Override
    public Integer saveZJWifiDevice(ZJDeviceRegisterRequest request) {
        Integer count = 0;
        String spId = request.getSpId();
        //设备号是否唯一
        List<Dtu> dtus = checkIMEI(request.getImei());
        if ((!CollectionUtil.isEmpty(dtus) && dtus.get(0).getIsDeleted() == 0) || dtus.size() > 1)
            throw new BizException("设备号已存在");
        //新增
        Dtu dtu = new Dtu();
        dtu.setId(request.getImei());
        dtu.setIMEI(request.getImei());
        dtu.setParentImei(request.getImei());
        dtu.setEquipmentManufacturer(request.getEquipmentManufacturer());
        dtu.setEquipmentType(request.getEquipmentType());
        dtu.setEquipmentModel(request.getEquipmentModel());
        dtu.setIccid(request.getIccid());
        dtu.setOperators(request.getOperators());
        dtu.setCommunicationMode(request.getCommunicationMode());
        dtu.setDetectionType("CH₄;");
        dtu.setProtocolVersion("v2.0");
        dtu.setEquipmentFrom(0);
        //dtu.setDeviceNo(Constants.ZJ_DEVICE_NO);
        dtu.setSpId(spId);
        dtu.setInstallTime(new Date());
        dtu.setCreateYM(Integer.parseInt(DateUtil.format(new Date(), yyMM)));
        dtu.setIsDeleted(0);
        dtu.setDeviceCode(request.getDeviceCode());
        dtu.setInstallationAddress("");
        String path = dtuMapper.selectPath(spId);
        if (!StringUtils.isEmpty(path)) dtu.setPath(path);

        dtu.setNetInTime(dtu.getRegisterTime());
        dtu.setCmpRegistered(1);
        Map<String, Object> equipmentId = getEquipmentId(request.getEquipmentManufacturer()
                , request.getOperators(), request.getEquipmentType(), null,request.getImei());
        dtu.setSerialNumber(equipmentId.get("serialNumber") + "");
        dtu.setValidity(5);
        dtu.setExpirationTime(DateUtil
                .offsetMonth(DateUtil.parse(dtu.getRegisterTime()), dtu.getValidity() * 12).toString(format));
        if (!CollectionUtil.isEmpty(dtus)) {
            Dtu d = dtus.get(0);
            UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().eq(Dtu::getId, d.getId())
                    .eq(Dtu::getIMEI, request.getImei());
            dtu.setIMEI(d.getId());
            dtu.setConsumerId(0);
            dtu.setSectorType(Constants.BLANK);
            dtu.setExpirationTime("");
            count = dtuMapper.update(dtu, updateWrapper);
        } else {
            dtu.setRegisterTime(DateUtil.format(new Date(), EquipmentServiceImpl.format));
            count = dtuMapper.insert(dtu);
        }

        cmpRegisterUpdate(dtu, 0);
        //操作日志log-24
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_24.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(dtu.getId());
        logVO.setOperationPersonCode("智慧厨房");
        logVO.setOperationPersonName("smartKitchen");
        logVO.setSpId(spId);
        operationLogService.insertLog(logVO);
        return count;
    }


    /**
     * 紫荆设备新增
     *
     * @param imei
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveEquipment(String imei) {
        log.info("saveEquipment-imei:{}", imei);
        Dtu dtu = dtuMapper.selectByImei(imei, "");
        if (dtu == null) {
            log.error("saveEquipment-dtu:{}", dtu);
            return;
        }
        Map<String, Object> equipmentId = getEquipmentId(Constants.ZJ_EQUIPMENT_MANUFACTURER
                , "", "", null,imei);
        dtu.setDeviceCode(imei);
        dtu.setSerialNumber(equipmentId.get("serialNumber") + "");
        dtu.setOperators("");
        dtu.setCommunicationMode("WiFi");
        dtu.setValidity(5);
        dtu.setIccid("");
        dtu.setExpirationTime(DateUtil
                .offsetMonth(DateUtil.parse(dtu.getRegisterTime()), dtu.getValidity() * 12).toString(format));
        UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(Dtu::getIsDeleted, 0)
                .eq(Dtu::getIMEI, imei);
        dtuMapper.update(dtu, updateWrapper);
        cmpRegisterUpdate(dtu, 0, Constants.ZJ_EQUIPMENT_DEVICETYPE);
        List<DtuAep> dtuAepList = dtuAepMapper.selectCmpListByImei(imei, dtu.getSpId());
        if (!CollectionUtils.isEmpty(dtuAepList)) {
            for (DtuAep dtuAep : dtuAepList) {
                dtuAep.setActivateTime(dtu.getRegisterTime());
                dtuAep.setActivateStatus(1);
                dtuAep.setOpenStatus(1);
                dtuAep.setOpenTime(dtu.getRegisterTime());
                dtuAepMapper.updateById(dtuAep);
            }
        }
    }

    /**
     * 紫荆设备删除
     *
     * @param imei
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeZJWifiDevice(String imei, String spId) {
        log.info("removeZJWifiDevice-imei:{},spId:{}", imei, spId);
        List<String> ids = new ArrayList<>();
        ids.add(imei);
        //删除aep
        List<Map<String, String>> list = dtuAepMapper.selectDeviceIds(ids);
        log.info("removeEquipment-list:{}", JSONObject.toJSONString(list));
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, Object> res = equipmentCmpService.cmpRequest(new HashMap<>(), 2,
                    equipmentCmpService.getHeaders(Constants.ZJ_EQUIPMENT_DEVICETYPE), imei);
            log.info("removeEquipment——res,响应结果：{}",
                    JSONObject.toJSONString(res));
//            if ((boolean) res.get("result")) {
//                deleteDtuAep(imei);
//            } else {
//                throw new BizException("cmp删除设备失败" + res.get("msg"));
//            }
            deleteDtuAep(imei);
        }

        List<Dtu> dtus = dtuMapper.selectByEquipmentIds(ids, spId);
        if (CollectionUtils.isEmpty(dtus)) {
            log.info("removeZJWifiDevice-dtus:{}", JSONObject.toJSONString(dtus));
            return;
        }
        dtuMapper.deleteByImei(imei);
        LambdaUpdateWrapper<ReceiverValve> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(ReceiverValve::getDeviceId, imei).eq(ReceiverValve::getSpId, spId);
        ReceiverValve receiverValve = new ReceiverValve();
        receiverValve.setIsDeleted(1);
        receiverValveMapper.update(receiverValve, updateWrapper);
    }


    /**
     * 编辑设备
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editEquipment(EditDeviceRequest request) {
        //校验
        String imei = request.getImei();
        Dtu dt = dtuMapper.selectByImei(imei, null);
        if (dt != null && dt.getIMEI() != null) {
            throw new BizException("设备已被客户绑定，请先解绑");
        }
        int validity = request.getValidity();
        if (validity < 0) throw new BizException("设备有效期为正整数");

        String loopPoint = request.getLoopPoint();
        String protocolVersion = request.getProtocolVersion();
        if (protocolVersion == null || (!protocolVersion.equals("v1.0") && !protocolVersion.equals("v2.0")))
            throw new BizException("输入协议版本有误");
        checkLoopPoint(loopPoint);
        Dtu dtu = new Dtu();
        List<Dtu> dtus = checkIMEI(request.getImei());
        if (!CollectionUtil.isEmpty(dtus) && dtus.size() >= 2)
            throw new BizException("设备号已存在");
        Dtu d = dtuMapper.selectByEquipmentId(request.getEquipmentId());
        if (DeviceConstant.WiFi_COMMUNICATIONMODE
                .equals(request.getCommunicationMode())) {
            throw new BizException("紫荆设备无对应的操作项");
        }
        if (!d.getCommunicationMode().equals(request.getCommunicationMode()))
            throw new BizException("通讯方式不允许编辑");
        if (d != null && !d.getIMEI().equals(request.getImei())) {
            throw new BizException("设备号不允许编辑");
        }
        //更新
        List<Dtu> ds = checkICCID(request.getIccid());
        if (!CollectionUtil.isEmpty(ds) && ds.size() >= 2 ||
                (ds.size() == 1 && !request.getEquipmentId().equals(ds.get(0).getDeviceCode()))) {
            throw new BizException("ICCID已经存在");
        }
        BeanUtils.copyProperties(request, dtu);
        dtu.setIMEI(request.getImei());
        dtu.setId(request.getImei());
        dtu.setDeviceCode(request.getEquipmentId());
        dtu.setParentImei(request.getImei());
        if (StringUtils.isEmpty(d.getNetInTime())) {
            dtu.setNetInTime(DateUtil.format(d.getCreatedAt(),format));
            d.setNetInTime(DateUtil.format(d.getCreatedAt(),format));
        }
        if (dtu.getValidity()!=0&&StringUtils.isEmpty(d.getNetInTime())){
            dtu.setExpirationTime(DateUtil.format(DateUtil
                    .offsetMonth(DateUtil.parse(d.getNetInTime()), request.getValidity() * 12), format));
        }
       if (dtu.getValidity()==0&&
               !EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(request.getEquipmentType())){
           if (EquipmentType.HOME_GAS_DETECTOR.getCode()
                   .equals(request.getEquipmentType())) {
               dtu.setValidity(5);
           } else {
               dtu.setValidity(3);
           }
       }
        dtu.setDeviceCode(request.getEquipmentId());
        dtu.setLoopPoint(request.getLoopPoint());
        dtu.setIsDeleted(0);
        if (!StringUtils.isEmpty(dtu.getDetectionType()))
            dtu.setDetectionType(request.getDetectionType() + ";");
        if (EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equals(request.getEquipmentType())) {
            dtu.setIMEI(null);
            dtu.setId(null);
        }
        UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(Dtu::getIsDeleted, 0)
                .eq(Dtu::getDeviceCode, dtu.getDeviceCode());

        dtuMapper.update(dtu, updateWrapper);
        if (!EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(request.getEquipmentType())){
            d.setValidity(null);
            dtu.setValidity(null);
        }
        //操作日志log-26,27,28,29,30,31,32;
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(dtu.getIMEI());

        //比较哪些字段发生改变
        Field[] fields = d.getClass().getDeclaredFields();
        Map<String, String> compare = compareUtil.compare(fields, d, dtu);

        if (StringUtil.isNotEmpty(compare.get("iccid"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_26.getCode());
        }
        if (StringUtil.isNotEmpty(compare.get("equipmentManufacturer"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_27.getCode());
        }
        if (StringUtil.isNotEmpty(compare.get("equipmentType"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_28.getCode());
        }
        if (StringUtil.isNotEmpty(compare.get("loopPoint"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_29.getCode());
        }
        if (StringUtil.isNotEmpty(compare.get("equipmentModel"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_30.getCode());
        }
        if (StringUtil.isNotEmpty(compare.get("validity"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_31.getCode());
        }
        if (StringUtil.isNotEmpty(compare.get("remark"))) {
            logCodeList.add(OperationTypeEnum.OPERATION_TYPE_32.getCode());
        }
        if (CollectionUtil.isNotEmpty(logCodeList)) {
            logVO.setCodeList(logCodeList);
            operationLogService.insertLog(logVO);
        }

        //企业级操作日志
        LogVO vo = new LogVO();
        StringBuilder stringBuilder = new StringBuilder();
        String detail = LogUtil.compareEntity(dtu,d, Dtu.class);
        stringBuilder.append(detail);
        if (StringUtil.isNotEmpty(compare.get("loopPoint"))) {
            stringBuilder.append("回路信息：由【");
            String[] split = d.getLoopPoint().split(";");
            for (int i = 0; i < split.length; i++) {
                stringBuilder.append("回路").append(i).append("：").append(split[i]).append("点位");
                if (i < split.length -1){
                    stringBuilder.append(",");
                }
            }
            stringBuilder.append("】变更成【");
            String[] split2 = dtu.getLoopPoint().split(";");
            for (int i = 0; i < split2.length; i++) {
                stringBuilder.append("回路").append(i).append("：").append(split2[i]).append("点位");
                if (i < split2.length -1){
                    stringBuilder.append(",");
                }
            }
            stringBuilder.append("】");
        }
        vo.setDetail(stringBuilder.toString());
        LogRecordAspect.threadLocal.set(vo);

    }

    /**
     * 查询设备详情
     *
     * @param equipmentId
     * @return
     */
    @Override
    public DtuInfoResponse equipmentInfo(String equipmentId) {
        Dtu dtu = dtuMapper.selectByEquipmentId(equipmentId);
        if (dtu == null) throw new BizException("数据不存在");
        DtuInfoResponse dtuInfoResponse = new DtuInfoResponse();
        if (dtu != null) {
            List<String> points = new ArrayList<>();
            BeanUtils.copyProperties(dtu, dtuInfoResponse);
            dtuInfoResponse.setEquipmentId(dtu.getDeviceCode());
            String loopPoint = dtu.getLoopPoint();
            if (!StringUtils.isEmpty(loopPoint)) {
                String[] split = loopPoint.split(EquipmentServiceImpl.split);
                points = new ArrayList(Arrays.asList(split));
            }

            dtuInfoResponse.setPoints(points);
            List<String> detectionTypes = new ArrayList<>();
            if (!StringUtils.isEmpty(dtu.getDetectionType())
                    && dtu.getDetectionType().contains(split)) {
                String[] split = dtu.getDetectionType().split(EquipmentServiceImpl.split);
                detectionTypes = new ArrayList(Arrays.asList(split));
            }
            dtuInfoResponse.setDetectionTypes(detectionTypes);
            QueryWrapper<ReceiverValve> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().or().eq(ReceiverValve::getSpId, dtu.getSpId())
                    .eq(ReceiverValve::getIsDeleted, 0)
                    .eq(ReceiverValve::getDeviceId, dtu.getIMEI());
            List<ReceiverValve> receiverValves = receiverValveMapper.selectList(queryWrapper);
            if (!CollectionUtil.isEmpty(receiverValves)) {
                ReceiverValveResponse receiverValveResponse = new ReceiverValveResponse();
                BeanUtils.copyProperties(receiverValves.get(0), receiverValveResponse);
                dtuInfoResponse.setResponse(receiverValveResponse);
            }
            // 服务信息
            QueryWrapper<ConsumerServiceInfo> serviceInfoWrapper = new QueryWrapper<>();
            serviceInfoWrapper.lambda().eq(ConsumerServiceInfo::getSpId, dtu.getSpId())
                    .eq(ConsumerServiceInfo::getIsDeleted, 0)
                    .eq(ConsumerServiceInfo::getImei, org.apache.commons.lang3.StringUtils.substringBefore(dtu.getIMEI(), "-"));
            List<ConsumerServiceInfo> consumerServiceInfoList = consumerServiceInfoMapper.selectList(serviceInfoWrapper);
            Long today = DateUtils.today().getTime();
            if (CollectionUtil.isNotEmpty(consumerServiceInfoList)) {
                ConsumerServiceInfo serviceInfo = consumerServiceInfoList.get(0);
                if (today <= serviceInfo.getEndDate().getTime() && serviceInfo.getEndDate().getTime() - today <= 30*24*60*60*1000L) {
                    dtuInfoResponse.setServiceStatus(1);
                } else if (today > serviceInfo.getEndDate().getTime()) {
                    dtuInfoResponse.setServiceStatus(2);
                } else {
                    dtuInfoResponse.setServiceStatus(0);
                }
            }
        }
        return dtuInfoResponse;
    }


    /**
     * 查询设备详情
     *
     * @param iMEI
     * @return
     */
    @Override
    public LoopInfoResponse equipmentInfo(String iMEI, int source) {
        Dtu dtu = dtuMapper.selectByImei(iMEI, "");
        if (dtu == null) throw new BizException("数据不存在");
        LoopInfoResponse dtuInfoResponse = new LoopInfoResponse();
        BeanUtils.copyProperties(dtu, dtuInfoResponse);
        List<String> query = getQueryParams();
        List<Map<String, String>> customerCode = dictMap(null, query, null);
        dtuInfoResponse.setEquipmentType(dtu.getEquipmentType());
        dtuInfoResponse.setEquipmentTypeCode(getStringValue(customerCode,
                dtu.getEquipmentType(), query.get(1), "value", "alias"));
        String detectionType = dtu.getDetectionType();
        dtuInfoResponse.setDetectionType(setDetection(query, customerCode, detectionType));
        dtuInfoResponse.setIMEI(dtu.getIMEI());
        LoopInfoResponse loops = loops(iMEI);
        dtuInfoResponse.setLoopAmount(loops.getLoopAmount());
        dtuInfoResponse.setImeis(loops.getImeis());
        return dtuInfoResponse;
    }

    @Override
    public Map<String, Integer> loopAmount(@Valid LoopAmountRequest request) {
        Map<String, Integer> res = new HashMap<>();
        List<String> imeis = request.getImeis();
        if (!CollectionUtil.isEmpty(imeis)) {
            imeis.forEach(s -> {
                List<Dtu> dtus = dtuMapper.selectLoop(s);
                if (!CollectionUtil.isEmpty(dtus)) {
                    res.put(s, dtus.size() - 1);
                }
            });
        }
        return res;
    }

    /**
     * 校验设备是否存在
     *
     * @param imei
     * @return
     */
    @Override
    public Map<String, Object> checkEquipment(String imei) {
        Map<String, Object> resultMap = new HashMap<>();
        boolean exist = true;
        Dtu dtu = dtuMapper.selectByImei(imei, "");
        log.info("checkEquipment-dtu:{}", JSONObject.toJSONString(dtu));
        if (dtu == null || StringUtils.isEmpty(dtu.getIMEI())) {
            exist = false;
        }
//        resultMap.put("imei",dtu.getIMEI());
        resultMap.put("exist", exist);
        return resultMap;
    }

    @Override
    public List<String> equipmentModels(String manufacturer) {
        String spId = ApplicationUtils.getWorkingSpId();
        return dtuMapper.selectEquipmentModel(manufacturer, spId);
    }

    /**
     * 批量设备删除
     *
     * @param ids
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void equipmentDelete(List<String> ids) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<Dtu> dtus = dtuMapper.selectByEquipmentIds(ids, spId);
        List<String> imeis = new ArrayList<>();
        if (!CollectionUtil.isEmpty(dtus)) {
            //企业级日志
            StringBuilder sb = new StringBuilder();
            StringBuilder sb1 = new StringBuilder();
            sb.append("【设备号：");
            dtus.forEach(dtu -> sb.append(dtu.getIMEI()).append(";"));
            dtus.forEach(dtu -> sb1.append(dtu.getIMEI()).append("\n"));
            sb.append("】");
            LogVO vo = new LogVO();
            if (dtus.size() > 1){
                vo.setOperateRecordEnum(OperateRecordEnum.OPERATE_TYPE_15);
            }
            vo.setDetail(sb.toString());
            vo.setCommonInfo(sb1.deleteCharAt(sb1.length()-1).toString());
            LogRecordAspect.threadLocal.set(vo);

            Long collect = dtus.stream().filter(dtu -> {
                if (DeviceConstant.WiFi_COMMUNICATIONMODE
                        .equals(dtu.getCommunicationMode())) {
                    throw new BizException("请检查删除的设备项");
                }
                imeis.add(dtu.getIMEI());
                return dtu.getConsumerId() != 0;
            }).collect(Collectors.counting());
            if (collect > 0) throw new BizException("设备已被客户关联，若需删除请先解除绑定");
        }

        log.info("equipmentDelete-ids:{}", JSONObject.toJSONString(ids));
        if (!CollectionUtil.isEmpty(ids)) {
            //删除aep
            List<Map<String, String>> list = dtuAepMapper.selectDeviceIds(ids);
            log.info("equipmentDelete-list:{}", JSONObject.toJSONString(list));
            if (!CollectionUtil.isEmpty(list)) {
                log.info("equipmentDelete-remove start");
                for (Map<String, String> s : list) {
                    String deviceId = s.get("device_id");
                    String deviceCode = s.get("deviceCode");
                    if (StringUtils.isEmpty(deviceId)) continue;
                    int deviceType= "NB".equals(s.get("communicationMode"))?0:1;
                    int header = Constants.UNICOM_EQUIPMENT_DEVICETYPE;
                    if (deviceType == Constants.CAT_EQUIPMENT_DEVICETYPE) header = 1;
                    if (s.get("protocol_version") == null || s.get("protocol_version").equals("v1.0")) {
                        header = Constants.TELECOM_EQUIPMENT_DEVICETYPE;
                    }else {
                        if (deviceType == 0) {
                            if (2 == Integer.parseInt(s.get("operators"))) header = Constants.MOVE_EQUIPMENT_DEVICETYPE;
                            if (3 == Integer.parseInt(s.get("operators")))
                                header = Constants.TELECOM_EQUIPMENT_DEVICETYPE;
                        }
                    }
                    Map<String, Object> res = equipmentCmpService.cmpRequest(new HashMap<>(), 2,
                            equipmentCmpService.getHeaders(header), deviceCode);
                    log.info("aepRegister——res,响应结果：{}",
                            JSONObject.toJSONString(res));
//                    if ((boolean) res.get("result")) {
//                        deleteDtuAep(deviceId);
//                    } else {
//                        if ("1009".equals(res.get("code"))){
//                            deleteDtuAep(deviceId);
//                        }else {
//                            log.info("equipmentDelete-log:{}",res.get("msg"));
//                        }
//                    }
                    deleteDtuAep(deviceId);
                }
            }
            dtuMapper.updateByIds(ids);
            if (!CollectionUtil.isEmpty(imeis)) dtuMapper.updateByImei(imeis);
            Map<String, List<Dtu>> collect = dtus.stream()
                    .collect(Collectors.groupingBy(Dtu::getEquipmentType, Collectors.toList()));
            collect.forEach((s, ds) -> {
                if (s.equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
                    ds.forEach(dtu -> {
                        deviceStateMapper.updateByImei(dtu.getIMEI(), dtu.getSpId());
                    });
                } else {
                    ds.forEach(dtu -> {
                        DeviceState deviceState = new DeviceState();
                        deviceState.setDeviceId(dtu.getIMEI());
                        deviceState.setDetectorCount(0);
                        deviceState.setMainBatteryValue(0);
                        deviceState.setDeviceStatus(0);
                        deviceState.setDeviceStatusInfo("");
                        UpdateWrapper<DeviceState> wrapper = new UpdateWrapper<>();
                        wrapper.lambda().or().eq(DeviceState::getDeviceId, dtu.getIMEI());
                        deviceStateMapper.update(deviceState, wrapper);
                    });
                }

            });
        }

        //操作日志log-33
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_33.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(dtu.name());
        logVO.setTableKey(ids.toString());
        operationLogService.insertLog(logVO);
    }

    @Override
    public void equipmentDelete(String id, String spId) {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        List<Dtu> dtus = dtuMapper.selectByEquipmentIds(ids, spId);
        if (CollectionUtil.isEmpty(dtus)) {
            throw new BizException("设备不存在，请检测设备是否正常" + id);
        }
        List<String> imeis = new ArrayList<>();
        if (!CollectionUtil.isEmpty(dtus)) {
            //企业级日志
            StringBuilder sb = new StringBuilder();
            StringBuilder sb1 = new StringBuilder();
            sb.append("【设备号：");
            dtus.forEach(dtu -> sb.append(dtu.getIMEI()).append(";"));
            dtus.forEach(dtu -> sb1.append(dtu.getIMEI()).append("\n"));
            sb.append("】");
            LogVO vo = new LogVO();
            if (dtus.size() > 1){
                vo.setOperateRecordEnum(OperateRecordEnum.OPERATE_TYPE_15);
            }
            vo.setDetail(sb.toString());
            vo.setCommonInfo(sb1.deleteCharAt(sb1.length()-1).toString());
            LogRecordAspect.threadLocal.set(vo);

            Long collect = dtus.stream().filter(dtu -> {
                if (DeviceConstant.WiFi_COMMUNICATIONMODE
                        .equals(dtu.getCommunicationMode())) {
                    throw new BizException("请检查删除的设备项");
                }
                imeis.add(dtu.getIMEI());
                return dtu.getConsumerId() != 0;
            }).collect(Collectors.counting());
            if (collect > 0) throw new BizException("设备已被客户关联，若需删除请先解除绑定");
        }

        log.info("equipmentDelete-ids:{}", JSONObject.toJSONString(ids));
        // 删除aep相关的代码
        if (!CollectionUtil.isEmpty(ids)) {
            //删除aep
            List<Map<String, String>> list = dtuAepMapper.selectDeviceIds(ids);
            log.info("equipmentDelete-list:{}", JSONObject.toJSONString(list));
            if (!CollectionUtil.isEmpty(list)) {
                log.info("equipmentDelete-remove start");
                for (Map<String, String> s : list) {
                    String deviceId = s.get("device_id");
                    if (StringUtils.isEmpty(deviceId)) continue;
//                    if (s.get("protocol_version") == null || s.get("protocol_version").equals("v1.0")) {
//                        aepRemove(deviceId);
//                    } else {
                        int header = Constants.UNICOM_EQUIPMENT_DEVICETYPE;
                        if (2==Integer.parseInt(s.get("operators")) ){
                            header=Constants.MOVE_EQUIPMENT_DEVICETYPE;
                        } else if (3==Integer.parseInt(s.get("operators")) ){
                            header=Constants.TELECOM_EQUIPMENT_DEVICETYPE;
                        }
                        Map<String, Object> res = equipmentCmpService.cmpRequest(new HashMap<>(), 2,
                                equipmentCmpService.getHeaders(header), deviceId);
                        log.info("aepRegister——res,响应结果：{}",
                                JSONObject.toJSONString(res));
//                        if ((boolean) res.get("result")) {
//                            deleteDtuAep(deviceId);
//                        } else {
//                            if ("1009".equals(res.get("code"))){
//                                deleteDtuAep(deviceId);
//                            }else {
//                                log.info("equipmentDelete-log:{}",res.get("msg"));
//                            }
//                        }
                        deleteDtuAep(deviceId);
//                    }
                }
            }
            dtuMapper.updateByIds(ids);
            if (!CollectionUtil.isEmpty(imeis)){
                dtuMapper.updateByImei(imeis);
            }
            Map<String, List<Dtu>> collect = dtus.stream()
                    .collect(Collectors.groupingBy(Dtu::getEquipmentType, Collectors.toList()));
            collect.forEach((s, ds) -> {
                if (s.equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
                    ds.forEach(dtu -> {
                        deviceStateMapper.updateByImei(dtu.getIMEI(), dtu.getSpId());
                    });
                } else {
                    ds.forEach(dtu -> {
                        DeviceState deviceState = new DeviceState();
                        deviceState.setDeviceId(dtu.getIMEI());
                        deviceState.setDetectorCount(0);
                        deviceState.setMainBatteryValue(0);
                        deviceState.setDeviceStatus(0);
                        UpdateWrapper<DeviceState> wrapper = new UpdateWrapper<>();
                        wrapper.lambda().or().eq(DeviceState::getDeviceId, dtu.getIMEI());
                        deviceStateMapper.update(deviceState, wrapper);
                    });
                }

            });
        }
        //操作日志log-24
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_33.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(dtu.name());
        logVO.setTableKey(ids.toString());
        logVO.setOperationPersonCode("智慧厨房");
        logVO.setOperationPersonName("smartKitchen");
        logVO.setSpId(spId);
        operationLogService.insertLog(logVO);
    }

    private void deleteDtuAep(String deviceId) {
        DtuAep dtuAep = new DtuAep();
        dtuAep.setDeviceId(deviceId);
        dtuAep.setIsDeleted(true);
        UpdateWrapper<DtuAep> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(DtuAep::getDeviceId, deviceId);
        dtuAepMapper.update(dtuAep, wrapper);
    }

    @Override
    public PageUtil<ConsumerDtuHistoryResponse> bindingHistory(ConsumerDtuHistoryRequest request) {
        List<ConsumerDtuHistoryResponse> res = new ArrayList<>();
        String spId = ApplicationUtils.getWorkingSpId();
//      if (request.getBindChannel()!=null) request.setBindChannel(request.getBindChannel()+1);
        Page<ConsumerDtuHistory> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        List<ConsumerDtuHistory> consumerDtuHistories = consumerDtuHistoryMapper.selectListByImei(request.getImei(), spId,
                request.getCustAddress(), request.getCustName(), request.getCustPhone()
                , request.getEvent(), request.getIndustryType(), request.getSubsCode(),
                request.getBindChannel()
        );
        log.info("bindingHistory-consumerDtuHistories:{}", JSONObject.toJSONString(consumerDtuHistories));
        consumerDtuHistories.forEach(consumerDtuHistory -> {
            ConsumerDtuHistoryResponse dtuHistoryResponse = new ConsumerDtuHistoryResponse();
            BeanUtils.copyProperties(consumerDtuHistory, dtuHistoryResponse);
            dtuHistoryResponse.setOperationPersonCode(consumerDtuHistory.getOperationPersonName() +
                    "(" + consumerDtuHistory.getOperationPersonCode() + ")");
            dtuHistoryResponse.setOperationPersonName(consumerDtuHistory.getOperationPersonName() +
                    "(" + consumerDtuHistory.getOperationPersonCode() + ")");
            dtuHistoryResponse.setCId(consumerDtuHistory.getConsumerId() + "");
            dtuHistoryResponse.setConsumerSeq(consumerDtuHistory.getConsumerSeq());
            String chanel = "";
            if (consumerDtuHistory.getBindChannel() == 2) {
                chanel = "时刻助手";
            } else if (consumerDtuHistory.getBindChannel() == 3) {
                chanel = "时刻助手";
            } else if (consumerDtuHistory.getBindChannel() == 5) {
                chanel = "TCIS3.0退货";
            } else {
                chanel = "手动";
            }
            dtuHistoryResponse.setBindChannel(chanel);
            res.add(dtuHistoryResponse);

        });
        PageUtil pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), res);
        return pageInfo;
    }

    @Override
    public PageUtil<DtuListResponse> bindEquipmentList(EquipmentListRequest request) {
        request.setOpenStatus(0);
        String spId = ApplicationUtils.getWorkingSpId();
        Page<Dtu> page = PageHelper.startPage(request.getPage(), request.getPageSize());

        List<Dtu> dtus = new ArrayList<>();
        List<DtuListResponse> responses = new ArrayList<>();
        Dtu dtu = new Dtu();
        BeanUtils.copyProperties(request, dtu);
        dtu.setIMEI(request.getImei());
        dtu.setSpId(spId);
        List<Map<String, Object>> maps = dtuMapper.selectBindListByCondition(dtu, null
                , request.getActivateStatus(), request.getOpenStatus(), request.getRegisterStatus());
        log.info("bindEquipmentList-maps:{}",JSONObject.toJSON(maps));
        //转化类
        maps.forEach(stringObjectMap -> {
            DtuListResponse dt = EntityUtils.mapToEntity(stringObjectMap, DtuListResponse.class);
            responses.add(dt);

        });

        Map<String, String> dtuMap = new HashMap<>();
        responses.forEach(d -> {
            dtuMap.put(d.getIMEI(), d.getDetectionType());
        });
        if (!CollectionUtil.isEmpty(responses)) {
            for (DtuListResponse d : responses) {
                if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(d.getEquipmentType())) {
                    RecordController recordController = recordControllerMapper.selectByImei(d.getId(), d.getSpId());
                    List<Map<String, Object>> objects = new ArrayList<>();
                    if (recordController != null) {
                        d.setLoopAmount(recordController.getDetectorCount());
                        List<RecordDetector> detectors = recordDetectorMapper
                                .selectByRecordIdAndDeviceId(recordController.getId(), recordController.getDeviceId());
                        detectors.forEach(o -> {
                            Map<String, Object> exts = new HashMap<>();
                            Integer subId = o.getSubId();
                            exts.put("iMEI", d.getIMEI() + Constants.EQUIPMENTI_CONSTANT + subId);
                            exts.put("loop", 1);
                            exts.put("point", o.getSubId());
                            exts.put("detectionType", dtuMap.get(exts.get("iMEI"))
                                    == null ? "CO" : dtuMap.get(exts.get("iMEI")));
                            objects.add(exts);
                        });
                        d.setExts(objects);
                    }
                }
            }
        }
        List<String> query = getQueryParams();
        List<Map<String, String>> customerCode = dictMap(null, query, null);
        //字典转换：
        responses.forEach(d -> {
            String equipmentManufacturer = d.getEquipmentManufacturer();
            String equipmentType = d.getEquipmentType();
            String communicationMode = d.getCommunicationMode();
            String detectionType = d.getDetectionType();
            String operators = d.getOperators();
            d.setEquipmentManufacturer(getStringValue(customerCode,
                    equipmentManufacturer, query.get(0), "value", "alias"));
            d.setEquipmentType(getStringValue(customerCode,
                    equipmentType, query.get(1), "value", "alias"));
            d.setCommunicationMode(getStringValue(customerCode,
                    communicationMode, query.get(3), "value", "alias"));
            d.setOperators(getStringValue(customerCode,
                    operators, query.get(2), "value", "alias"));
            d.setDetectionType(setDetection(query, customerCode, detectionType));
        });

        log.info("bindEquipmentList-responses:{}",JSONObject.toJSON(responses));
        PageUtil pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), responses);
        return pageInfo;
    }

    @Override
    public List<ConsumerStatusResponse> consumerStatus() {
        String spId = ApplicationUtils.getWorkingSpId();
        //获取所有客户
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<Consumer> consumerList = consumerMapper.selectList(consumerQueryWrapper);
        List<ConsumerStatusResponse> responses = BeanConvertUtils.convertListTo(consumerList, ConsumerStatusResponse::new);
        return responses;


    }

    @Override
    public PageUtil<ConsumerEquipmentResponse> consumerEquipment(ComsumerEquipmentRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        String consumerId = request.getConsumerId();
        Consumer consumer = consumerService.getById(request.getConsumerId());
        if (consumer != null) {
            spId = consumer.getSpId();
        }
        //获取设备列表, 根据IMEI升序排列
        List<ConsumerEquipmentResponse> equipmentVOList = new ArrayList<>();
        Page<HistoryAlarmVo> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        QueryWrapper<Dtu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Dtu::getConsumerId, consumerId)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Dtu::getSpId, spId)
                .orderByAsc(Dtu::getIMEI)
                .like(StringUtil.isNotEmpty(request.getImei()), Dtu::getIMEI, request.getImei())
                .like(StringUtil.isNotEmpty(request.getEquipmentName()), Dtu::getName, request.getEquipmentName())
                .like(StringUtil.isNotEmpty(request.getInstallationPosition()), Dtu::getInstallationPosition, request.getInstallationPosition())
                .like(StringUtil.isNotEmpty(request.getEquipmentModel()), Dtu::getEquipmentModel, request.getEquipmentModel())
                .eq(StringUtil.isNotEmpty(request.getEquipmentManufacturer()), Dtu::getEquipmentManufacturer, request.getEquipmentManufacturer())
                .eq(StringUtil.isNotEmpty(request.getEquipmentType()), Dtu::getEquipmentType, request.getEquipmentType())
                .eq(StringUtil.isNotEmpty(request.getOperators()), Dtu::getOperators, request.getOperators())
                .eq(StringUtil.isNotEmpty(request.getCommunicationMode()), Dtu::getCommunicationMode, request.getCommunicationMode());

        //当模板二查询条件有订单号
        if (StringUtil.isNotEmpty(request.getOutOrderCode())) {
            QueryWrapper<DtuBindingOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(DtuBindingOrder::getOutOrderCode, request.getOutOrderCode())
                    .eq(DtuBindingOrder::getSpId, spId)
                    .eq(DtuBindingOrder::getIsDeleted, IS_DELETED_FALSE);
            List<DtuBindingOrder> orderList = dtuBindingOrderMapper.selectList(queryWrapper);
            List<String> deviceIdList = orderList.stream().map(DtuBindingOrder::getDeviceId).collect(Collectors.toList());
            wrapper.lambda().in(CollectionUtil.isNotEmpty(deviceIdList), Dtu::getId, deviceIdList);
        }
        List<Dtu> dtuList = this.list(wrapper);
        // 当存在关联设备
        if (CollectionUtil.isNotEmpty(dtuList)) {
            List<String> imeiList = new ArrayList<>();
            dtuList.stream().forEach(x -> {
                imeiList.add(org.apache.commons.lang3.StringUtils.substringBefore(x.getIMEI(), "-"));
            });
            //查服务信息
            QueryWrapper<ConsumerServiceInfo> consumerServiceInfoWrapper = new QueryWrapper<>();
            consumerServiceInfoWrapper.lambda().in(ConsumerServiceInfo::getImei, imeiList)
                    .eq(ConsumerServiceInfo::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(ConsumerServiceInfo::getSpId, spId);
            List<ConsumerServiceInfo> consumerServiceInfoList = consumerServiceInfoService.list(consumerServiceInfoWrapper);
            Map<String, ConsumerServiceInfo> consumerServiceInfoMap = new HashMap<>();
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(consumerServiceInfoList)) {
                consumerServiceInfoList.stream().forEach(item -> {
                    consumerServiceInfoMap.put(item.getImei(), item);
                });
            }
            //查询设备信息
            Map<String, Integer> imeiMap = new HashMap<>();
            List<Dtu> queriedByimeis = dtuMapper.queryByimeis(imeiList);
            if (!CollectionUtils.isEmpty(queriedByimeis)) {
                //计算控制器下的探头数量
                for (Dtu queriedByimei : queriedByimeis) {
                    if (queriedByimei.getIMEI().contains("-")) {
                        String imei = queriedByimei.getIMEI().split("-")[0];
                        if (imeiMap.containsKey(imei)) {
                            imeiMap.put(imei, imeiMap.get(imei) + 1);
                        } else {
                            imeiMap.put(imei, 1);
                        }
                    }
                }
            }
            //设备厂商名称
            ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", response);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
                supplierListVos = response.getData();
            }
            //根据设备id 查询最后一次设备状态 ;运营商字典,检测类型字典
            for (Dtu dtu : dtuList) {
                ConsumerEquipmentResponse vo = new ConsumerEquipmentResponse();
                BeanUtils.copyProperties(dtu, vo);
                ConsumerServiceInfo consumerServiceInfo = null;
                if (vo.getIMEI().contains("-")) {
                    consumerServiceInfo = consumerServiceInfoMap.get(org.apache.commons.lang.StringUtils.substringBefore(vo.getIMEI(), "-"));
                } else {
                    consumerServiceInfo = consumerServiceInfoMap.get(vo.getIMEI());
                    vo.setProbeSum(imeiMap.get(vo.getIMEI()));
                    log.info("列表查询家庭成员" + vo.getIMEI());
                    ConsoleSkUserListResponse consoleSkUserListResponse = consoleSkFeignClient
                            .alarmSOSUserList(vo.getIMEI());
                    log.info(new StringBuilder().append("需要给").append(vo.getIMEI()).append("的家庭成员发送信息，信息如下").append(consoleSkUserListResponse).toString());;
                    if (consoleSkUserListResponse != null && consoleSkUserListResponse.getData() != null
                            && CollectionUtil.isNotEmpty(consoleSkUserListResponse.getData().getUserList())) {
                        vo.setIsBindC("Y");
                    }else {
                        vo.setIsBindC("N");
                    }
                    if (StringUtils.isEmpty(consumer.getSubsCode()) && StringUtils.pathEquals("Y", request.getIsDeleteConsumer())) {
                        vo.setIsDeleteConsumer("Y");
                    } else {
                        vo.setIsDeleteConsumer("N");
                    }
                }
                if (consumerServiceInfo != null) {
                    vo.setServiceInfo(consumerServiceInfo.getServiceInfo());
                    vo.setStartDate(DateUtils.format(consumerServiceInfo.getStartDate(), DateUtils.DATE_FORMAT));
                    vo.setEndDate(DateUtils.format(consumerServiceInfo.getEndDate(), DateUtils.DATE_FORMAT));
                    Long today = DateUtils.today().getTime();
                    if (today == consumerServiceInfo.getEndDate().getTime()) {
                        vo.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_4.getCode());
                    }  else if (today < consumerServiceInfo.getEndDate().getTime()) {
                        if (consumerServiceInfo.getEndDate().getTime() - today <= 7*24*60*60*1000) {
                            vo.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_3.getCode());
                        } else if (consumerServiceInfo.getEndDate().getTime() - today <= 30*24*60*60*1000L) {
                            vo.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_2.getCode());
                        } else {
                            vo.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_1.getCode());
                        }
                    } else if (today > consumerServiceInfo.getEndDate().getTime()) {
                        if (today - consumerServiceInfo.getEndDate().getTime() <= 7*24*60*60*1000) {
                            vo.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_5.getCode());
                        } else {
                            vo.setServiceStatus(ConsumerServiceStatusEnum.CONSUMER_SERVICE_STATUS_6.getCode());
                        }
                    }
                    vo.setServiceStatusName(ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(vo.getServiceStatus()) == null ?
                            "" : ConsumerServiceStatusEnum.getConsumerServiceStatusEnum(vo.getServiceStatus()).getName());

                }
                vo.setEquipmentId(dtu.getDeviceCode());
                vo.setInstallDate(dtu.getInstallDate());
                //控制器的点位数
                if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(dtu.getEquipmentType())) {
                    DeviceStateVO deviceStateVO = deviceStateService.getDeviceStateByImei(dtu.getIMEI(), dtu.getSpId());
                    vo.setPoint(deviceStateVO.getDetectorCount());
                }

                vo.setEquipmentTypeCode(dtu.getEquipmentType());
                //运营商,设备类型,检测类型,设备厂商
                String equipmentType = consumerService.dictionaryname(dtu.getEquipmentType(), "Equipment_type");
                vo.setEquipmentType(equipmentType);
                String operator = consumerService.dictionaryname(dtu.getOperators(), Constants.OPERATOR_CODE);
                vo.setOperators(operator);

                //检测类型存在多种;
                if (StrUtil.isNotBlank(dtu.getDetectionType())) {
                    String[] typeList = dtu.getDetectionType().split(";");
                    StringBuffer stringBuffer = new StringBuffer("");
                    for (String type : typeList) {
                        stringBuffer.append(consumerService.dictionaryname(type, Constants.DETECTION_TYPE_CODE) + "、");
                    }
                    vo.setDetectionType(stringBuffer.toString()
                            .substring(0, stringBuffer.length() - 1));
                }
                //String manufacturer = consumerService.dictionaryname(dtu.getEquipmentManufacturer(), "Equipment_manufacturer");
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        dtu.getEquipmentManufacturer())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    vo.setEquipmentManufacturer(listVos.get(0).getMsName());
                }

                LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
                if (latestLog == null) {
                    vo.setEquipmentStatus(null);  // 状态
                    vo.setEquipmentStatusInfo(null);  //状态信息
                    vo.setLatestTime(null);          // 最近上报时间
                    vo.setVoltage(null);                    // 电压
                    vo.setSignal(null);                  // 信号情况
                    vo.setXLEL(null);
                    equipmentVOList.add(vo);
                    continue;
                }
                log.info("latestLog : {}", latestLog.toString());
                //判断设备类型,赋值
                //新增紫荆字段
                if (latestLog.getValveStatus() != null) vo.setValveStatus(ValveStatusEnum.parse(latestLog.getValveStatus()).name());
                if (latestLog.getReceiverStatus() != null) vo.setReceiverStatus(latestLog.getReceiverStatus()==0?"离线":"正常");
                vo.setEquipmentStatus(latestLog.getEquipmentStatus());  // 状态
                vo.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo());  //状态信息
                vo.setLatestTime(latestLog.getLatestTime());
                vo.setVoltage(latestLog.getBtV());
                vo.setSignal(SignalEnum.getName(latestLog.getSignal()));
                vo.setXLEL(latestLog.getXlel());
                vo.setLonLat(vo.getPositionLon()+";"+vo.getPositionLat());
                //判断设备是否有电磁阀
                vo.setHasValve(dtu.getValveInfoId() == 0 ? "-" : "有");
                vo.setValveInfoId(dtu.getValveInfoId());
                vo.setValueExist(dtu.getValveInfoId() == 0 ? 1 : 0);
                equipmentVOList.add(vo);
            }
            log.info("detail: 设备信息:{}", equipmentVOList.toString());

            List<Integer> valveInfoIds = equipmentVOList.stream().map(ConsumerEquipmentResponse::getValveInfoId).collect(Collectors.toList());
            commonService.loadFieldAndPackaging(equipmentVOList, ConsumerEquipmentResponse.class,null, valveInfoIds, null, spId,PageListCode.CUSTOMER_MANAGE_DETAIL.getCode());
        }
        List<FieldListShowResponse> responses = fieldListShowService.queryListShowByShowStatus(PageListCode.CUSTOMER_MANAGE_DETAIL.getCode(), spId);
        List<String> fields = responses.stream().map(FieldListShowResponse::getFieldCode).collect(Collectors.toList());
        List<String> titles = responses.stream().map(FieldListShowResponse::getFieldName).collect(Collectors.toList());
        List<PageColumns> add = PageColumnConst.add(titles.toArray(new String[]{}), fields.toArray(new String[]{}));
        PageUtil pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), equipmentVOList, add);
        return pageInfo;
    }

    @Override
    public PageUtil<ConsumerBindingHistoryResponse> consumerBindingHistory(ConsumerBindingHistoryRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getPageSize());
        Dtu dtu = new Dtu();
        BeanUtil.copyProperties(request, dtu);
        List<Map<String, Object>> responses = dtuMapper.consumerBindingHistory(dtu, request.getConsumerId(),
                request.getEvent(), spId, request.getOutOrderCode(), request.getBindChannel());
        ArrayList<ConsumerBindingHistoryResponse> list = new ArrayList<>();
        responses.forEach(r -> {
            ConsumerBindingHistoryResponse entity = EntityUtils.mapToEntity(r, ConsumerBindingHistoryResponse.class);
            list.add(entity);
        });
        //字典转换
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        List<DictionaryItemRespDTO> detectionTypeDTOList = holder.getDictionaryByKey(DETECTION_TYPE_CODE);
        List<DictionaryItemRespDTO> operatorDTOList = holder.getDictionaryByKey(OPERATOR_CODE);
        List<DictionaryItemRespDTO> communicationModeDTOList = holder.getDictionaryByKey(COMMUNICATION_Mode_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse listResponse = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", listResponse);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (listResponse != null && listResponse.getCode() == 0 && listResponse.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(listResponse.getData())) {
            supplierListVos = listResponse.getData();
        }


        for (ConsumerBindingHistoryResponse response : list) {
            AlarmSupplierListVo supplierListVo = supplierListVos.stream()
                    .filter(d -> d.getAlarmSystemCode().equals(response.getEquipmentManufacturer()))
                    .collect(Collectors.toList()).get(0);
            DictionaryItemRespDTO equipmentTypeDTO = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(response.getEquipmentType()))
                    .collect(Collectors.toList()).get(0);
            log.info("response.getOperators():{}", response.getOperators());
            DictionaryItemRespDTO operatorDTO = operatorDTOList.stream()
                    .filter(d -> d.getValue().equals(response.getOperators()))
                    .collect(Collectors.toList()).get(0);
            DictionaryItemRespDTO communicationModeDTO = communicationModeDTOList.stream()
                    .filter(d -> d.getValue().equals(response.getCommunicationMode()))
                    .collect(Collectors.toList()).get(0);

            response.setEquipmentManufacturer(supplierListVo.getMsName());
            response.setEquipmentType(equipmentTypeDTO.getName());
            response.setEvent(response.getEventCode().equals(0) ? "解除关联" : "关联");
            switch (response.getBindChannelCode()) {
                case 1:
                    response.setBindChannel("手动");
                    break;
                case 2:
                    response.setBindChannel("时刻助手");
                    break;
                case 3:
                    response.setBindChannel("时刻助手");
                    break;
                case 4:
                    response.setBindChannel("智慧厨房");
                    break;
                case 5:
                    response.setBindChannel("TCIS3.0退货");
                    break;
            }
            //检测类型存在多种;
            if (StrUtil.isNotBlank(response.getDetectionType())) {
                String[] typeList = response.getDetectionType().split(";");
                StringBuffer stringBuffer = new StringBuffer("");

                for (String type : typeList) {
                    DictionaryItemRespDTO detectionTypeDTO = detectionTypeDTOList.stream()
                            .filter(d -> d.getValue().equals(type))
                            .collect(Collectors.toList()).get(0);
                    stringBuffer.append(detectionTypeDTO.getName() + "、");
                }
                response.setDetectionType(stringBuffer.toString()
                        .substring(0, stringBuffer.length() - 1));
            }
            response.setOperators(operatorDTO.getName());
            response.setCommunicationMode(communicationModeDTO.getName());
            //工单编号和工单类型
            LambdaQueryWrapper<WorkOrderHistory> lqw = new LambdaQueryWrapper<>();
            lqw.eq(WorkOrderHistory::getHandleStatus, 1).eq(WorkOrderHistory::getIsDeleted, IS_DELETED_FALSE)
                    .eq(WorkOrderHistory::getSpId, spId)
                    .and(lqw1 -> lqw1.and(querryWrapper -> querryWrapper.eq(WorkOrderHistory::getOrderType, 1).eq(WorkOrderHistory::getDeviceId, response.getIMEI()))
                            .or(querryWrapper ->  querryWrapper.eq(WorkOrderHistory::getOrderType, 3).eq(WorkOrderHistory::getNewDeviceId, response.getIMEI())))
                    .orderByDesc(WorkOrderHistory::getUpdatedAt);
            log.info(lqw.getSqlSegment());
            List<WorkOrderHistory> histories = workOrderHistoryService.list(lqw);
            log.info("历史记录为：{}", histories);
            if (!CollectionUtil.isEmpty(histories)){
                WorkOrderHistory history = histories.get(0);
                if (response.getBindChannelCode() != 1 && response.getBindChannelCode() != 4) {
                    response.setWorkerOrderId(history.getOrderNo());
                    if (history.getOrderChannel() == 0){
                        response.setOrderType(MbpConst.WORK_ORDER_OUTER_BUY);
                    }else if (history.getOrderType() == 1){
                        response.setOrderType(MbpConst.WORK_ORDER_INNER_BUY);
                    }else if (history.getOrderType() ==  3){
                        response.setOrderType(MbpConst.WORK_ORDER_INNER_REPAIR);
                    }
                }

            }

        }
        PageUtil<ConsumerBindingHistoryResponse> pageUtil = new PageUtil<>();
        pageUtil.setList(list);
        pageUtil.setPageSize(request.getPageSize());
        pageUtil.setPage(request.getPage());
        pageUtil.setTotal(page.getTotal());
        return pageUtil;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Dtu deviceInfo(Map<String,Dtu> dtuMap, String imei, String point) {
        log.info("deviceInfo-requestParam:{},{},{}", JSONObject.toJSONString(dtuMap), imei, point);
        if (StringUtils.isEmpty(imei) || StringUtils.isEmpty(point)) return null;
        Dtu dtu = null;
        try {
            //控制器
            Dtu controllerD = dtuMap.getOrDefault(imei, null);
            if (controllerD == null){
                log.info("deviceInfo-nonentity:{},{}", imei, controllerD);
                return null;
            }
            Dtu d = new Dtu();
            BeanUtils.copyProperties(controllerD, d);
            log.info("deviceInfo-d:{}", JSONObject.toJSONString(d));
            if (d.getIsDeleted() == 1) {
                log.info("deviceInfo-nonentity:{},{}", imei, d);
                return null;
            }
            //探测器
            if (v2.equals(d.getProtocolVersion())) {
                d.setIMEI(imei + Constants.EQUIPMENTI_CONSTANT + point);
                d.setId(imei + Constants.EQUIPMENTI_CONSTANT + point);
            } else if (v1.equals(d.getProtocolVersion())) {
                String loop = "";
                if (point.length() < 2) {
                    loop = "1";
                } else {
                    loop = point.substring(0, 1);
                }
                d.setIMEI(imei + "-" + loop + "-" + point.substring(1, point.length()));
                d.setId(imei + "-" + loop + "-" + point.substring(1, point.length()));
            }
            d.setParentImei(imei);
            dtu = dtuMap.getOrDefault(d.getIMEI(),null);
            if (dtu != null && dtu.getIsDeleted() == 0) return dtu;

            d.setConsumerId(d.getConsumerId());
            d.setEquipmentType(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode());
            d.setName("");
            d.setInstallTime(new Date());
            d.setDeviceCode(d.getDeviceCode() + Constants.EQUIPMENTI_CONSTANT + point);
            d.setIsDeleted(0);
            d.setValidity(3);
            if (dtu != null && dtu.getIsDeleted() == 1) {
                UpdateWrapper<Dtu> wrapper = new UpdateWrapper<>();
                wrapper.lambda().eq(Dtu::getIsDeleted, 1).eq(Dtu::getIMEI, d.getIMEI());
                dtuMapper.update(d, wrapper);
            } else {
                dtuMapper.insert(d);
            }
            // 如果是余杭设备, 就注册到余杭
            if (d.getSpId().equals(hangzhouSpId)) {
                consumerService.registerCityDevice(d.getSpId(), d.getIMEI());
            }
            dtu = d;
            //更新客户点位数
            Consumer consumer = consumerMapper.selectById(d.getConsumerId());
            if (consumer != null && consumer.getId() != null) {
                Integer count = dtuMapper.selectCountByConsumerId(consumer.getId());
                consumer.setPointTotal(count);
                consumerMapper.updateById(consumer);
            }
        } catch (Exception e) {
            log.error("deviceInfo-error:", e);
        }
        return dtu;
    }


    @Override
    public Dtu getDeviceByImei(String imei, String spId) {
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getId, imei)
                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId);
        Dtu dtu = dtuMapper.selectOne(queryWrapper);
        return dtu;
    }

    @Override
    public List<Dtu> queryDeviceByImei(List<String> imeiList, String spId) {
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Dtu::getId, imeiList)
                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId);
        List<Dtu> dtuList = dtuMapper.selectList(queryWrapper);
        return dtuList;
    }

    @Override
    public Dtu getDeviceByImeiAndSpIds(String imei, List<String> spIds) {
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getId, imei)
                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE)
                .in(Dtu::getSpId, spIds);
        Dtu dtu = dtuMapper.selectOne(queryWrapper);
        return dtu;
    }

    @Override
    public List<Dtu> getAllDtuById(String deviceId) {
        List<Dtu> list = null;
        try {
            QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Dtu::getId, deviceId)
                    .eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
            Dtu dtu = this.getOne(queryWrapper);
            QueryWrapper<Dtu> wrapper = new QueryWrapper<>();
            wrapper.lambda().likeRight(Dtu::getIMEI, dtu.getIMEI())
                    .eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
            list = this.list(wrapper);
        } catch (Exception e) {
            log.info("根据deviceId:{},未查询到设备,error:{}", deviceId, e.getMessage());
        }
        return list;

    }

    public List<Dtu> queryEquipmentList(LatestLogListRequest request) {
        return dtuMapper.getDetectorList(request.getImei(), request.getEquipmentName(),
                request.getEquipmentTypes(), request.getSpId(), request.getImeiList(), request.getSubsCode(),
                request.getCustName(), request.getCustAddress(), request.getCustPhone(), request.getIndustryType(),
                request.getEquipmentModel(), request.getEquipmentManufacturer());
    }

    @Override
    public List<Dtu> listEquipmentWithType1(LatestLogListRequest request) {
        return dtuMapper.getDetectors(request.getImei(), request.getEquipmentName(),
                request.getEquipmentTypes(), request.getSpId(), request.getImeiList(), request.getSubsCode(),
                request.getCustName(), request.getCustAddress(), request.getCustPhone(), request.getIndustryType(),
                request.getEquipmentModel(), request.getEquipmentManufacturer(), request.getOrgCode(), request.getCustomerAddress());
    }

    @Override
    public List<ConsumerEquipmentResponse> consumerEquipmentAsst(ComsumerEquipmentRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<ConsumerEquipmentResponse> responseList = consumerEquipment(request).getList();
        List<String> deviceIds = responseList.stream().map(ConsumerEquipmentResponse::getId).collect(Collectors.toList());
        //关联 工单信息表
        if (CollectionUtil.isNotEmpty(deviceIds)) {
            QueryWrapper<DtuBindingOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(DtuBindingOrder::getDeviceId, deviceIds)
                    .eq(DtuBindingOrder::getSpId, spId)
                    .eq(DtuBindingOrder::getIsDeleted, IS_DELETED_FALSE);
            List<DtuBindingOrder> orderList = dtuBindingOrderMapper.selectList(queryWrapper);
            for (ConsumerEquipmentResponse response : responseList) {
                OrderInfoResponse infoResponse = new OrderInfoResponse();
                for (DtuBindingOrder order : orderList) {
                    if (order.getDeviceId().equals(response.getId())) {
                        BeanUtil.copyProperties(order, infoResponse);
                    }
                }
                response.setOrderInfoResponse(infoResponse);
            }
        }
        return responseList;
    }

    @Override
    public void editInstallationAddress(EquipmentAddressRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getSpId, spId)
                .eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
        List<Dtu> dtus = dtuMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(dtus)) {
            throw new BizException("该设备不存在");
        }
        Dtu dtu = new Dtu();
        dtu.setPositionLon(request.getPositionLon());
        dtu.setPositionLat(request.getPositionLat());
        dtu.setInstallationAddress(request.getInstallationAddress());
        dtuMapper.update(dtu, queryWrapper);

        //操作日志log-23
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_23.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(request.getImei());
        logVO.setOperationBefore(dtus.get(0).getInstallationAddress());
        logVO.setOperationAfter(request.getInstallationAddress());
        operationLogService.insertLog(logVO);
    }

    /**
     * 获取点位信息
     *
     * @param iMEI
     * @return
     */
    public LoopInfoResponse loops(String iMEI) {
        LoopInfoResponse loopInfoResponse = new LoopInfoResponse();
        loopInfoResponse.setIMEI(iMEI);
        List<String> loops = new ArrayList<>();
        if (!StringUtils.isEmpty(iMEI)) {
            List<Dtu> dtus = dtuMapper.selectLoop(iMEI);
            if (!CollectionUtil.isEmpty(dtus)) {
                loopInfoResponse.setLoopAmount(dtus.size() - 1);
                dtus.forEach(dtu -> {
                    if ("Point_type_gas_detector".equals(dtu.getEquipmentType())) {
                        loops.add(dtu.getIMEI());
                    }
                });
            } else {
                loopInfoResponse.setLoopAmount(0);
            }
        }
        loopInfoResponse.setImeis(loops);
        return loopInfoResponse;
    }


    @Override
    public List<DtuResponse> clientDtuListBySubs(ClientDtuListRequest request, String spId, FieldTemplate template) {
        log.info("clientDtuListBySubs request: {}, spId: {}, template: {}", request, spId, template);
        Consumer consumer = null;
        //模板一且传入户号(紫荆用户没有户号)
        if (template.getTemplateType().equals(Constants.BIND_CHANNEL_GAS) && StringUtil.isNotEmpty(request.getSubsCode())) {
            //判断户号是否存在
            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
            consumerQueryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .eq(Consumer::getSpId, spId);
            List<Consumer> consumerList = consumerMapper.selectList(consumerQueryWrapper);
            if (consumerList.isEmpty()) {
                log.info(request.getSubsCode() + "户号查询不到对应客户.");
                return null;
            }
            consumer = consumerList.get(0);
        } else if (StringUtil.isNotEmpty(request.getPhone())) {
            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
            consumerQueryWrapper.lambda().eq(Consumer::getPhone, request.getPhone())
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
            if (StringUtils.isEmpty(request.getUserId())) {// 非智慧厨房紫荆wifi报警器 区分组织
                consumerQueryWrapper.lambda().eq(Consumer::getSpId, spId);
            } else {//智慧厨房紫荆wifi报警器 userId绑定紫荆wifi报警器
                consumerQueryWrapper.lambda().eq(Consumer::getMemberId, request.getUserId());
            }
            List<Consumer> consumerList = consumerMapper.selectList(consumerQueryWrapper);
            if (consumerList.isEmpty()) {
                log.info(request.getPhone() + "手机号查询不到对应客户.");
                return null;
            }
            consumer = consumerList.get(0);
        }

        //根据户号查询 客户得到设备列表
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getConsumerId, consumer.getId())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId)
                .orderByAsc(Dtu::getIMEI);
        //获取设备列表
        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
        if (CollectionUtil.isEmpty(dtuList)) {
            log.info("客户id:{} 未绑定设备", consumer.getId());
            return null;
        }
        //运行报告配置
        Integer configuration = null;
        BusinessNotice notice = noticeService.getByCode("h5_running_record", spId);
        if (notice != null &&  "ON".equals(notice.getParamValue())){
            configuration = 0;
        }else {
            configuration = 1;
        }
        //运行报告配置
        Integer serviceConfiguration = null;
        BusinessNotice serviceNotice = noticeService.getByCode("h5_service_state", spId);
        if (serviceNotice != null &&  "ON".equals(serviceNotice.getParamValue())){
            serviceConfiguration = 0;
        }else {
            serviceConfiguration = 1;
        }
        ArrayList<DtuResponse> dtuResponses = new ArrayList<>();
        // 服务信息
        log.info("h5equipment imeis: {}", dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList()));
        QueryWrapper<ConsumerServiceInfo> serviceInfoWrapper = new QueryWrapper<>();
        serviceInfoWrapper.lambda().eq(ConsumerServiceInfo::getSpId, spId)
                .eq(ConsumerServiceInfo::getIsDeleted, 0)
                .in(ConsumerServiceInfo::getImei, dtuList.stream().map(Dtu::getIMEI).collect(Collectors.toList()));
        List<ConsumerServiceInfo> consumerServiceInfoList = consumerServiceInfoMapper.selectList(serviceInfoWrapper);
        log.info("h5equipment consumerServiceInfoList: {}", consumerServiceInfoList);
        Map<String, Integer> serviceStatusMap = new HashMap<>();
        Long today = DateUtils.today().getTime();
        if (CollectionUtil.isNotEmpty(consumerServiceInfoList)) {
            consumerServiceInfoList.stream().forEach(x -> {
                log.info("h5equipment imei: {},today: {},endDate: {}", x.getImei(), today, x.getEndDate().getTime());
                if (today <= x.getEndDate().getTime() && x.getEndDate().getTime() - today <= 30*24*60*60*1000L) {
                    serviceStatusMap.put(x.getImei(), 1);
                } else if (today > x.getEndDate().getTime()) {
                    serviceStatusMap.put(x.getImei(), 2);
                } else {
                    serviceStatusMap.put(x.getImei(), 0);
                }
            });

        }
        for (Dtu dtu : dtuList) {
            DictionaryItemRespDTO equipmentTypeCode = holder.getDictionaryItemBySpId(
                    Constants.EQUIPMENT_TYPE_CODE, spId).stream().filter(a -> a.getValue().equals(
                    dtu.getEquipmentType())).collect(Collectors.toList()).get(0);
            LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
            DtuResponse dtuResponse = new DtuResponse();
            dtuResponse.setId(dtu.getId());
            dtuResponse.setImei(dtu.getIMEI());
            dtuResponse.setName(dtu.getName());
            dtuResponse.setInstallationPosition(dtu.getInstallationPosition());
            dtuResponse.setEquipmentType(equipmentTypeCode.getName());
            dtuResponse.setEquipmentStatus(latestLog.getEquipmentStatus());
            dtuResponse.setEquipmentFrom(dtu.getEquipmentFrom());
            dtuResponse.setConfiguration(configuration);
            dtuResponse.setServiceConfiguration(serviceConfiguration);
            dtuResponse.setServiceStatus(serviceStatusMap.get(dtu.getIMEI()) == null ? 0 : serviceStatusMap.get(dtu.getIMEI()));
            LambdaQueryWrapper<RunningStrategyReport> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RunningStrategyReport::getIsDeleted,0).eq(RunningStrategyReport::getIMEI,dtu.getIMEI());
            Integer integer = reportMapper.selectCount(queryWrapper);
            log.info("clientDtuListBySubs-integer:{}",integer);
            if (integer>0){
                dtuResponse.setDispaly(0);
            }else {
                dtuResponse.setDispaly(1);
            }

            dtuResponses.add(dtuResponse);
        }

        //对控制器设备状态数量进行设置
        List<DtuResponse> list = dtuResponses.stream()
                .filter(d -> d.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getName()))
                .collect(Collectors.toList());
        for (DtuResponse response : list) {
            //获取控制器imei
            String imei = org.apache.commons.lang3.StringUtils.substringBefore(response.getImei(), "-");
            Iterator<DtuResponse> responseIterator = dtuResponses.iterator();
            while (responseIterator.hasNext()) {
                DtuResponse next = responseIterator.next();
                if (next.getImei().equals(imei)) {
                    //0:离线 1:正常 2:低报 3:高报 4:故障 5:过期 6:设备无信号归属于离线，没有入库6这个值
                    switch (response.getEquipmentStatus()) {
                        case 0 :
                            next.setOfflineSum(next.getOfflineSum() == null ? 1 : next.getOfflineSum() + 1);
                            break;
                        case 1:
                            next.setNormalSum(next.getNormalSum() == null ? 1 : next.getNormalSum() + 1);
                            break;
                        case 2:
                            next.setAlarmSum(next.getAlarmSum() == null ? 1 : next.getAlarmSum() + 1);
                            break;
                        case 3:
                            next.setAlarmSum(next.getAlarmSum() == null ? 1 : next.getAlarmSum() + 1);
                            break;
                        case 4:
                            next.setFaultSum(next.getFaultSum() == null ? 1 : next.getFaultSum() + 1);
                            break;
                        case 6 :
                            next.setOfflineSum(next.getOfflineSum() == null ? 1 : next.getOfflineSum() + 1);
                            break;
                    }
                }
            }
        }

        return dtuResponses;
    }

    /**
     * 智慧厨房获取设备列表
     *
     * @param request
     * @return
     */
    @Override
    public List<IotskDtuResponse> clientDtuListIotSk(InnerDtuListRequest request) {
        log.info("clientDtuListBySubs request: {}, spId: {}, template: {}", request);
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getMemberId, request.getUserId())
                .or(i -> i.eq(Consumer::getSubsCode, request.getSubsCode()).eq(Consumer::getSpId, request.getSpId()))
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<Consumer> consumerList = consumerMapper.selectList(consumerQueryWrapper);
        if (consumerList.isEmpty()) {
            log.info("户号:{},时刻家用户ID:{},查询不到对应客户", request.getSubsCode(), request.getUserId());
            return null;
        }
        List<Integer> consumerIds = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
        //根据户号查询 客户得到设备列表
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        if (request.getSourceType() != null && request.getSourceType() == 1) {//B 端获取设备列表
            dtuQueryWrapper.lambda().in(Dtu::getConsumerId, consumerIds)
                    .eq(Dtu::getSpId, request.getSpId())
                    .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                    .orderByAsc(Dtu::getIMEI);
        }
        dtuQueryWrapper.lambda().in(Dtu::getConsumerId, consumerIds)
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .orderByAsc(Dtu::getIMEI);
        //获取设备列表
        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
        if (CollectionUtil.isEmpty(dtuList)) {
            log.info("客户id:{} 未绑定设备", consumerIds);
            return null;
        }

        List<Dtu> controllerList = dtuList.stream().filter(
                dtu -> !EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equalsIgnoreCase(dtu.getEquipmentType())
        ).collect(Collectors.toList());

        List<Dtu> detectorList = dtuList.stream().filter(
                dtu -> EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equalsIgnoreCase(dtu.getEquipmentType())
        ).collect(Collectors.toList());

        Map<String,List<Dtu>> detectorMap = detectorList.stream().collect(
                Collectors.groupingBy(dtu -> {
                    if( !StringUtils.isEmpty(dtu.getIMEI()) ){
                        return StringUtils.split(dtu.getIMEI(),"-")[0];
                    }else{
                        return dtu.getIMEI();
                    }
                })
        );

        List<IotskDtuResponse> dtuResponses = new ArrayList<>();
        for (Dtu con : controllerList) {
            LatestLog latestLog = latestLogService.get(con.getIMEI(), con.getSpId());
            IotskDtuResponse dtuResponse = new IotskDtuResponse();
            dtuResponse.setImei(con.getIMEI());
            dtuResponse.setEquipmentStatus(latestLog.getEquipmentStatus());
            dtuResponse.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo());
            dtuResponse.setEquipmentFrom(con.getEquipmentFrom());
            dtuResponse.setSignal(latestLog.getSignal());
            if( detectorMap.containsKey(con.getIMEI()) ){
                List<IotskDtuResponse> detectorDeviceList = new ArrayList<>();
                for ( Dtu detector : detectorMap.get(con.getIMEI()) ){
                    IotskDtuResponse detectorResponse = new IotskDtuResponse();
                    LatestLog latestLog1 = latestLogService.get(detector.getIMEI(), detector.getSpId());
                    detectorResponse.setImei(detector.getIMEI());
                    detectorResponse.setEquipmentStatus(latestLog1.getEquipmentStatus());
                    detectorResponse.setEquipmentStatusInfo(latestLog1.getEquipmentStatusInfo());
                    detectorResponse.setEquipmentFrom(detector.getEquipmentFrom());
                    detectorResponse.setSignal(latestLog1.getSignal());
                    detectorDeviceList.add(detectorResponse);
                }
                dtuResponse.setDetectorNum(detectorDeviceList.size());
                dtuResponse.setDetectorDeviceList(detectorDeviceList);
            }
            dtuResponses.add(dtuResponse);
        }
        return dtuResponses;
    }


//    @Override // for kitchen
//    public Map<String, List<DtuResponse>> clientDtuListBySubsArray(List<ClientDtuListRequest> requests, String spId, FieldTemplate template) {
//        List<Consumer> consumerList = Collections.emptyList();
//        if (template.getTemplateType().equals(Constants.BIND_CHANNEL_GAS)) {
//            //判断户号是否存在
//            List<String> subsCodes = requests.stream().map(ClientDtuListRequest::getSubsCode).collect(Collectors.toList());
//            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
//            consumerQueryWrapper.lambda().in(Consumer::getSubsCode, subsCodes)
//                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
//                    .eq(Consumer::getSpId, spId);
//            consumerList = consumerMapper.selectList(consumerQueryWrapper);
//            if (CollectionUtil.isEmpty(consumerList)) {
//                log.info("户号[{}]查询不到对应客户.", subsCodes);
//                return null;
//            }
//        } else if (template.getTemplateType().equals(Constants.BIND_CHANNEL_ASST)) {
//            QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
//            List<String> phones = requests.stream().map(ClientDtuListRequest::getPhone).collect(Collectors.toList());
//            consumerQueryWrapper.lambda().in(Consumer::getPhone, phones)
//                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
//                    .eq(Consumer::getSpId, spId);
//            consumerList = consumerMapper.selectList(consumerQueryWrapper);
//            if (CollectionUtil.isEmpty(consumerList)) {
//                log.info("手机号[{}]查询不到对应客户.", phones);
//                return null;
//            }
//        }
//
//        //根据户号查询 客户得到设备列表
//        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
//        List<Integer> consumerIds = consumerList.stream().map(Consumer::getId).collect(Collectors.toList());
//        dtuQueryWrapper.lambda().in(Dtu::getConsumerId, consumerIds)
//                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
//                .eq(Dtu::getSpId, spId)
//                .orderByAsc(Dtu::getIMEI);
//        //获取设备列表
//        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
//        if (CollectionUtil.isEmpty(dtuList)) {
//            log.info("客户id:[{}] 未绑定设备", consumerIds);
//            return null;
//        }
//        ArrayList<DtuResponse> dtuResponses = new ArrayList<>();
//        for (Dtu dtu : dtuList) {
//            DictionaryItemRespDTO equipmentTypeCode = holder.getDictionaryItemBySpId(
//                    Constants.EQUIPMENT_TYPE_CODE, spId).stream().filter(a -> a.getValue().equals(
//                    dtu.getEquipmentType())).collect(Collectors.toList()).get(0);
//            LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
//            DtuResponse dtuResponse = new DtuResponse();
//            dtuResponse.setId(dtu.getId());
//            dtuResponse.setImei(dtu.getIMEI());
//            dtuResponse.setName(dtu.getName());
//            dtuResponse.setInstallationPosition(dtu.getInstallationPosition());
//            dtuResponse.setEquipmentType(equipmentTypeCode.getName());
//            dtuResponse.setEquipmentStatus(latestLog.getEquipmentStatus());
//
//            Optional<Consumer> consumer = consumerList.stream().filter(
//                    it -> Objects.equals(it.getId(), dtu.getConsumerId())).findFirst();
//            if (template.getTemplateType().equals(Constants.BIND_CHANNEL_GAS)) {
//                dtuResponse.setSubsCode(consumer.get().getSubsCode());
//            } else if (template.getTemplateType().equals(Constants.BIND_CHANNEL_ASST)) {
//                dtuResponse.setPhone(consumer.get().getPhone());
//            }
//            dtuResponses.add(dtuResponse);
//        }
//        //对控制器设备状态数量进行设置
//        List<DtuResponse> list = dtuResponses.stream()
//                .filter(d -> d.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getName()))
//                .collect(Collectors.toList());
//        for (DtuResponse response : list) {
//            //获取控制器imei
//            String imei = org.apache.commons.lang3.StringUtils.substringBefore(response.getImei(), "-");
//
//            Iterator<DtuResponse> responseIterator = dtuResponses.iterator();
//            while (responseIterator.hasNext()) {
//                DtuResponse next = responseIterator.next();
//                if (next.getImei().equals(imei)) {
//                    //0:离线 1:正常 2:低报 3:高报 4:故障 5:过期
//                    switch (response.getEquipmentStatus()) {
//                        case 0:
//                            next.setOfflineSum(next.getOfflineSum() == null ? 1 : next.getOfflineSum() + 1);
//                            break;
//                        case 1:
//                            next.setNormalSum(next.getNormalSum() == null ? 1 : next.getNormalSum() + 1);
//                            break;
//                        case 2:
//                            next.setAlarmSum(next.getAlarmSum() == null ? 1 : next.getAlarmSum() + 1);
//                            break;
//                        case 3:
//                            next.setAlarmSum(next.getAlarmSum() == null ? 1 : next.getAlarmSum() + 1);
//                            break;
//                        case 4:
//                            next.setFaultSum(next.getFaultSum() == null ? 1 : next.getFaultSum() + 1);
//                            break;
//                    }
//                }
//            }
//        }
//
//        Map<String, List<DtuResponse>> results = Collections.emptyMap();
//        if (template.getTemplateType().equals(Constants.BIND_CHANNEL_GAS)) {
//            results = dtuResponses.stream().collect(Collectors.groupingBy(DtuResponse::getSubsCode));
//        } else if (template.getTemplateType().equals(Constants.BIND_CHANNEL_ASST)) {
//            results = dtuResponses.stream().collect(Collectors.groupingBy(DtuResponse::getPhone));
//        }
//
//        return results;
//    }

    /**
     * 设备列表
     *
     * @param request
     * @return
     */
    @Override
    public PageUtil<DtuListResponse> equipmentList(EquipmentListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        Page<Dtu> page = PageHelper.startPage(request.getPage(), request.getPageSize());

        List<DtuListResponse> responses = new ArrayList<>();
        EquipmentListParamVO paramVO = new EquipmentListParamVO();
        BeanUtils.copyProperties(request, paramVO);
        paramVO.setIMEI(request.getImei());
        paramVO.setSpId(spId);

        List<Map<String, Object>> maps = dtuMapper.selectListByCondition(paramVO);
        log.info("equipmentList-maps:{}", JSONObject.toJSONString(maps));
        //转化类
        List<String> imeis = new ArrayList<>();
        //查询主探测器
        List<String> imeiList = new ArrayList<>();
        Map<String, DtuListResponse> map = new HashMap<>();
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        //查询客户
        List<Integer> consumerIds = new ArrayList<>();
        Map<Integer, Consumer> consumerMap = new HashMap<>();
        maps.forEach(stringObjectMap -> {
            DtuListResponse dt = EntityUtils.mapToEntity(stringObjectMap, DtuListResponse.class);
            dt.setOpenStatus(!StringUtils.isEmpty(stringObjectMap.get("openStatus"))&&Integer.parseInt(stringObjectMap.get("openStatus")+"")==1?"已开通":"未开通");
            dt.setActivateStatus(!StringUtils.isEmpty(stringObjectMap.get("activateStatus"))&&Integer.parseInt(stringObjectMap.get("activateStatus")+"")==1?"已激活":"未激活");
            dt.setRegisterStatus(!StringUtils.isEmpty(stringObjectMap.get("registerStatus"))&&Integer.parseInt(stringObjectMap.get("registerStatus")+"")==1?"已注册":"未注册");
//            dt.setExistHistory(stringObjectMap.get("existHistory"));
            dt.setIccid(stringObjectMap.get("iccid")+"");
            responses.add(dt);
            if (EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(dt.getEquipmentType())) {
                map.put(stringObjectMap.get("iMEI") + "",dt);
                imeis.add(stringObjectMap.get("iMEI") + "");
            }
            if (EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equals(dt.getEquipmentType())) {
                String[] iMEIS = org.apache.commons.lang3.StringUtils.split(stringObjectMap.get("iMEI") + "", "-");
                imeiList.add(iMEIS[0]);
            }
            if (dt.getConsumerId() > 0) {
                consumerIds.add(dt.getConsumerId());
            }

        });
        log.info("equipmentList-imeiList:{}", JSONObject.toJSONString(imeiList));
        if (!CollectionUtils.isEmpty(imeiList)) {
            List<Map<String, Object>> imeiMaps = dtuMapper.selectListByImeiList(imeiList, spId);
            imeiMaps.forEach(stringObjectMap -> {
                DtuListResponse dt = EntityUtils.mapToEntity(stringObjectMap, DtuListResponse.class);
                dt.setOpenStatus(!StringUtils.isEmpty(stringObjectMap.get("openStatus"))&&Integer.parseInt(stringObjectMap.get("openStatus")+"")==1?"已开通":"未开通");
                dt.setActivateStatus(!StringUtils.isEmpty(stringObjectMap.get("activateStatus"))&&Integer.parseInt(stringObjectMap.get("activateStatus")+"")==1?"已激活":"未激活");
                dt.setRegisterStatus(!StringUtils.isEmpty(stringObjectMap.get("registerStatus"))&&Integer.parseInt(stringObjectMap.get("registerStatus")+"")==1?"已注册":"未注册");
                map.put(stringObjectMap.get("iMEI") + "",dt);
            });
        }
        if (!CollectionUtils.isEmpty(consumerIds)) {
            LambdaQueryWrapper<Consumer> query = new LambdaQueryWrapper<>();
            query.or().eq(Consumer::getIsDeleted,0).in(Consumer::getId, consumerIds);
            List<Consumer> consumers = consumerMapper.selectList(query);
            log.info("equipmentList-consumers:{}",JSONObject.toJSONString(consumers));
            if (!CollectionUtils.isEmpty(consumers)) {
                consumerMap = consumers.stream().collect(Collectors.toMap(Consumer::getId, Consumer -> Consumer, (a1, a2) -> a1));
            }
        }
        log.info("equipmentList-consumerMap:{}",JSONObject.toJSONString(consumerMap));
        log.info("equipmentList-map:{}",JSONObject.toJSONString(map));
        log.info("equipmentList-imeis:{}", JSONObject.toJSONString(imeis));
        Map<String, String> dtuMap = new HashMap<>();
        responses.forEach(d -> {
            dtuMap.put(d.getIMEI(), d.getDetectionType());
        });
        List<DictionaryItemRespDTO> dictionary = holder.getDictionaryByKey(Constants.INDUSTRY_TYPE_CODE);
        if (!CollectionUtil.isEmpty(responses)) {
            List<String> query = getQueryParams();
            List<Map<String, String>> customerCode = dictMap(null, query, null);
            for (DtuListResponse d : responses) {
                String equipmentManufacturer = d.getEquipmentManufacturer();
                String equipmentType = d.getEquipmentType();
                String communicationMode = d.getCommunicationMode();
                String detectionType = d.getDetectionType();
                String operators = d.getOperators();
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        equipmentManufacturer)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    d.setEquipmentManufacturer(listVos.get(0).getMsName());
                }

                d.setEquipmentType(getStringValue(customerCode,
                        equipmentType, query.get(1), "value", "alias"));
                d.setEquipmentTypeTag(equipmentType);
                d.setCommunicationMode(getStringValue(customerCode,
                        communicationMode, query.get(3), "value", "alias"));
                d.setOperators(getStringValue(customerCode,
                        operators, query.get(2), "value", "alias"));
                d.setDetectionType(setDetection(query, customerCode, detectionType));
                if (EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equals(equipmentType)) {
                    log.info("equipmentList-dtu:{}",JSONObject.toJSONString(d));
                    String imei = d.getIMEI();
                    if (imei.contains("-")){
                        String[] split = imei.split("-");
                        DtuListResponse dtuListResponse = map.get(split[0]);
                        log.info("equipmentList-dtuListResponse:{}",JSONObject.toJSONString(dtuListResponse));
                        if (dtuListResponse==null) continue;
                        if (dtuListResponse!=null){
                            d.setOpenStatus(dtuListResponse.getOpenStatus());
                            d.setRegisterStatus(dtuListResponse.getRegisterStatus());
                            d.setActivateStatus(dtuListResponse.getActivateStatus());
                            d.setRegisterTime(dtuListResponse.getRegisterTime());
                            d.setOpenTime(dtuListResponse.getOpenTime());
                            d.setActivateTime(dtuListResponse.getActivateTime());
                            d.setSignInTime(dtuListResponse.getSignInTime());
                            d.setExpirationTime(dtuListResponse.getExpirationTime());
                        }

                    }
                }

                if (consumerMap.containsKey(d.getConsumerId())) {
                    Consumer consumer = consumerMap.get(d.getConsumerId());
                    d.setSubsCode(consumer.getSubsCode());
                    d.setCustName(consumer.getCustName());
                    d.setCustAddress(consumer.getCustAddress());
                    d.setCustPhone(consumer.getCustPhone());
                    d.setCustType(consumer.getCustType());
                    d.setConsumerName(consumer.getName());
                    d.setCustAddress(consumer.getCustAddress());
                    d.setIndustryType(consumer.getIndustryType());
                    d.setIndustryTypeName(dictionaryService.getName(dictionary, consumer.getIndustryType()));
                }

            }
        }
        List<FieldListShowResponse> fieldsRes = fieldListShowService.queryListShowByShowStatus(PageListCode.EQUIPMENT_LIST.getCode(), spId);
        List<String> fields = fieldsRes.stream().map(FieldListShowResponse::getFieldCode).collect(Collectors.toList());
        List<String> titles = fieldsRes.stream().map(FieldListShowResponse::getFieldName).collect(Collectors.toList());
        List<PageColumns> add = PageColumnConst.add(titles.toArray(new String[]{}), fields.toArray(new String[]{}));
        PageUtil pageInfo = new PageUtil<>(request.getPage(), request.getPageSize(), page.getTotal(), responses,add);
        return pageInfo;
    }

    /**
     * 设备点位数据
     *
     * @param request
     * @return
     */
    @Override
    public List<Map<String, Object>> detectors(@Valid DetectorRequest request) {
        List<String> imeis = new ArrayList<>();
        imeis.add(request.getImei());
        String spId = ApplicationUtils.getWorkingSpId();
        List<Map<String, Object>> objects = new ArrayList<>();
        Map<Long, List<RecordDetector>> collect = new HashMap<>();

        List<Dtu> dtus = checkIMEI(request.getImei());
        if (CollectionUtils.isEmpty(dtus)) return objects;
        if (!CollectionUtils.isEmpty(imeis)) {
            List<Long> ids = recordDetectorMapper
                    .selectByRecordIdAndDeviceIds(imeis, spId, EquipmentType.GAS_ALARM_CONTROLLER.getCode());
            if (!CollectionUtils.isEmpty(ids)) {
                List<RecordDetector> detectors = recordDetectorMapper.selectByRecordId(ids);
                log.info("equipmentList-detectors:{}", JSONObject.toJSONString(detectors));
                collect = detectors.stream()
                        .collect(Collectors.groupingBy(RecordDetector::getRecordId, Collectors.toList()));
            }
            Dtu dtu = dtus.get(0);
            if (collect != null) {
                collect.forEach((aLong, recordDetectors) -> {
                        recordDetectors.forEach(o -> {
                            Map<String, Object> exts = new HashMap<>();
                            Integer subId = ((RecordDetector) o).getSubId();
                            exts.put("iMEI", ((RecordDetector) o).getDeviceId());
                            exts.put("loop", 1);
                            exts.put("point", subId);
                            exts.put("detectionType", dtu.getDetectionType()
                                    == null ? "CO" : dtu.getDetectionType());
                            objects.add(exts);
                        });
                });
            }
        }
        return objects;
    }

    @Override
    public void deviceSuitable(String imei) {
        int count=dtuMapper.deviceSuitable(imei);
        if (count>0)throw new BizException("当前设备不能进行置换操作");
    }

    @Override
    public void editInstallDate(EquipmentPositionRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();

        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getIMEI, request.getImei()).eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        Dtu oldDtu = this.getOne(queryWrapper);
        LambdaQueryWrapper<Consumer> query = new LambdaQueryWrapper<>();
        query.or().eq(Consumer::getIsDeleted,0).eq(Consumer::getId,oldDtu.getConsumerId());
        List<Consumer> consumers = consumerMapper.selectList(query);
        if (!CollectionUtils.isEmpty(consumers))workOrderHistoryService.existWorkOrder(consumers.get(0).getSubsCode(),spId);
        Dtu dtu = new Dtu();
        BeanUtils.copyProperties(oldDtu, dtu);
        dtu.setInstallDate(request.getInstallDate());
        this.updateById(dtu);

        QueryWrapper<ConsumerServiceInfo> serviceInfoQueryWrapper = new QueryWrapper<>();
        serviceInfoQueryWrapper.lambda().eq(ConsumerServiceInfo::getImei, request.getImei()).eq(ConsumerServiceInfo::getIsDeleted, Constants.IS_DELETED_FALSE);
        ConsumerServiceInfo oldConsumerServiceInfo = consumerServiceInfoService.getOne(serviceInfoQueryWrapper);
        log.info("修改设备安装日期，服务信息是否变更:{}",oldConsumerServiceInfo.getIsUpdate() == 0 ? "变" : "不变");
        if (oldConsumerServiceInfo.getIsUpdate() == 0) {
            try {
                oldConsumerServiceInfo.setStartDate(DateUtils.toDate(dtu.getInstallDate()));
                if (EquipmentType.HOME_GAS_DETECTOR.getCode().equals(dtu.getEquipmentType())){
                    oldConsumerServiceInfo.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 5));
                } else {
                    // 工商业报警器
                    oldConsumerServiceInfo.setEndDate(DateUtils.getDiffYearDate(DateUtils.toDate(dtu.getInstallDate()), 3));
                }
                consumerServiceInfoService.updateById(oldConsumerServiceInfo);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setConsumerId(oldDtu.getConsumerId().toString());
        vo.setDetail(LogUtil.compareEntity(dtu, oldDtu, Dtu.class));
        LogRecordAspect.threadLocal.set(vo);

    }

    @Override
    public List<IotskDtuResponse> alarmEquipmentListFor(ZJAlarmEquipmentRequest request) {
        if (CollectionUtil.isEmpty(request.getImeis())) {
            log.info("设备号不能为空:{} ", request.getImeis());
            return null;
        }
        //根据户号查询 客户得到设备列表
        List<Dtu> dtuList = dtuMapper.queryByimeis(request.getImeis());
        if (CollectionUtil.isEmpty(dtuList)) {
            log.info("设备不存在数据:{} ", request.getImeis());
            return null;
        }

        List<Dtu> controllerList = dtuList.stream().filter(
                dtu -> !EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equalsIgnoreCase(dtu.getEquipmentType())
        ).collect(Collectors.toList());

        List<Dtu> detectorList = dtuList.stream().filter(
                dtu -> EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode().equalsIgnoreCase(dtu.getEquipmentType())
        ).collect(Collectors.toList());

        Map<String,List<Dtu>> detectorMap = detectorList.stream().collect(
                Collectors.groupingBy(dtu -> {
                    if( !StringUtils.isEmpty(dtu.getIMEI()) ){
                        return StringUtils.split(dtu.getIMEI(),"-")[0];
                    }else{
                        return dtu.getIMEI();
                    }
                })
        );

        List<IotskDtuResponse> dtuResponses = new ArrayList<>();
        for (Dtu con : controllerList) {
            LatestLog latestLog = latestLogService.get(con.getIMEI(), con.getSpId());
            IotskDtuResponse dtuResponse = new IotskDtuResponse();
            dtuResponse.setImei(con.getIMEI());
            dtuResponse.setEquipmentStatus(latestLog.getEquipmentStatus());
            dtuResponse.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo());
            dtuResponse.setEquipmentFrom(con.getEquipmentFrom());
            dtuResponse.setSignal(latestLog.getSignal());
            if( detectorMap.containsKey(con.getIMEI()) ){
                List<IotskDtuResponse> detectorDeviceList = new ArrayList<>();
                for ( Dtu detector : detectorMap.get(con.getIMEI()) ){
                    IotskDtuResponse detectorResponse = new IotskDtuResponse();
                    LatestLog latestLog1 = latestLogService.get(detector.getIMEI(), detector.getSpId());
                    detectorResponse.setImei(detector.getIMEI());
                    detectorResponse.setEquipmentStatus(latestLog1.getEquipmentStatus());
                    detectorResponse.setEquipmentStatusInfo(latestLog1.getEquipmentStatusInfo());
                    detectorResponse.setEquipmentFrom(detector.getEquipmentFrom());
                    detectorResponse.setSignal(latestLog1.getSignal());
                    detectorDeviceList.add(detectorResponse);
                }
                dtuResponse.setDetectorNum(detectorDeviceList.size());
                dtuResponse.setDetectorDeviceList(detectorDeviceList);
            }
            dtuResponses.add(dtuResponse);
        }
        return dtuResponses;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void syncDtu() {
        int pageIndex = 1;
        int  pageSize = 500;
        long total = 0;
        do{
            Page<Dtu> pages = PageHelper.startPage(pageIndex, pageSize);
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().gt(Dtu::getPositionLat, 0)
                    .gt(Dtu::getPositionLon, 0);
            List<Dtu> dtuList = this.list(dtuQueryWrapper);
            pageIndex++;
            total = pages.getTotal();
            log.info("客户表高德转百度{},分页{},{}，{}",pageIndex, pages.getPages(), pages.getPageSize(), pages.getTotal());
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(dtuList)) {
                //开始修改坐标
                for (Dtu dtu : dtuList) {
                    if (dtu.getPositionLat() != null && dtu.getPositionLon() != null) {
                        List<BaiDuDetailResp> baiDuDetailResps = CoordinatesTransitionUtil.requestGetAK(dtu.getPositionLon() + "," + dtu.getPositionLat(), baiDuMapsKey);
                        if (!CollectionUtils.isEmpty(baiDuDetailResps)) {
                            dtu.setPositionLon(baiDuDetailResps.get(0).getX());
                            dtu.setPositionLat(baiDuDetailResps.get(0).getY());
                        }

                    }
                }
                this.saveOrUpdateBatch(dtuList);
            }
            dtuList.clear();
        }while(total > (pageIndex - 1) * pageSize);
    }

    @Override
    public String deviceImportData(MultipartFile file) {
        String spId = ApplicationUtils.getWorkingSpId();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        String uuid = IdUtil.fastSimpleUUID();
        log.info(uuid + " deviceImportData-timeStart:{}",System.currentTimeMillis());
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0); //指定输入流和sheet
        List<List<Object>> read = reader.read(1, reader.getRowCount());
        String username = ApplicationUtils.getWorkingUser().getUsername();
        String name = ApplicationUtils.getWorkingUser().getName();
        FileUpload fileUpload = new FileUpload();
        fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(username);
        fileUpload.setCreatorName(name);
        fileUpload.setUploadCode("UPLOAD0004");
        fileUpload.setSpId(spId);
        fileUpload.setUploadStatus("waiting");
        //上传文件路径
        String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
        log.info(uuid + " deviceImportData-url:{}",JSONObject.toJSONString(url));
        fileUpload.setUploadUrl(url);
        fileUploadMapper.insert(fileUpload);
        log.info(uuid + " deviceImportData-fileUpload:{}",JSONObject.toJSONString(fileUpload));
        Integer id = fileUpload.getId();
        // 从主线程获取用户数据 放到局部变量中
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        SecurityContext context = SecurityContextHolder.getContext();
        executor.submit(() -> {
            try {
                // 把旧RequestAttributes放到新线程的RequestContextHolder中
                RequestContextHolder.setRequestAttributes(attributes);
                SecurityContextHolder.setContext(context);
                importDtuDelete(file, spId, read, username, name, id, uuid);
                log.info(uuid + " deviceImportData-timeEnd:{}",System.currentTimeMillis());
            } catch (Exception e) {
                log.error(uuid + " deviceImportData-error:{}",e);
                FileUpload fileUpload1 = fileUploadMapper.selectById(id);
                if (fileUpload1 != null) {
                    fileUpload1.setUploadStatus("fail");
                    fileUploadMapper.updateById(fileUpload1);
                }

            }
        });
        LogVO vo = new LogVO();
        vo.setResultCode(Constants.OPERATE_RESULT_SUCCESS);
        LogRecordAspect.threadLocal.set(vo);
        log.info(uuid + " importData-return: {}", System.currentTimeMillis());
        return "";
    }

    public Integer importDtuDelete(MultipartFile file, String spId, List<List<Object>> read,String username,String name,Integer id, String uuid) {
        log.info(uuid + " deviceImportData-start......");
        List<Integer> errors = new ArrayList<>();
        Map<Integer, String> errorMap = new HashMap<>();
        log.info(uuid + " deviceImportData-data:{}", JSONObject.toJSONString(read));
        List<String> sumDtus = new ArrayList<>();
        int number = 0;
        for (int i = 0; i < read.size(); i++) {
            Integer errorSize= errorMap.size();
            List<Object> objects = read.get(i);
            if (ObjectUtils.isEmpty(objects.get(0))) {
                continue;
            }
            String imei = objects.get(0).toString();
            number = number + 1;
            //进行校验
            String res = checkDeviceDelete(imei, spId, errorMap, i+2);
            log.info(uuid + " deviceImportData-res:{}",res);
            if (res.equals("1")) {
                errors.add(i + 2);
                log.info(uuid + " deviceImportData-errors:{}",errors);
            } else if (!StringUtils.isEmpty(res)) {
                boolean  result=true;
                if (sumDtus.contains(imei)){
                    result=false;
                    errors.add(i + 2);
                    errorMap.put(i + 2,res+"在excel重复");
                    log.info(uuid + " updateDtus:{}",res+"在excel重复");
                }
                if (result){
                    sumDtus.add(imei);
                }
            }
            log.info(uuid + " deviceImportData-size:{}:errorMap{}",errorSize,errorMap.size());
        }

        log.info(uuid + " deviceImportData-errorMap",JSONObject.toJSONString(errorMap));
        FileUpload fileUpload = fileUploadMapper.selectById(id);
        fileUpload.setRowCount(number);
        fileUpload.setUploadTime(new Date());
        fileUpload.setId(id);
        log.info(uuid + " deviceImportData-fileUpload:{}",JSONObject.toJSONString(fileUpload));
//        try {
//            fileUpload.setRowCount(number);
//            fileUpload.setUploadTime(new Date());
//            fileUpload.setId(id);
//            log.info(uuid + " deviceImportData-fileUpload:{}",JSONObject.toJSONString(fileUpload));
//            //上传文件路径
//            //String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
//            //log.info(uuid + " deviceImportData-url:{}",JSONObject.toJSONString(url));
//            //fileUpload.setUploadUrl(url);
//            log.info(uuid + " deviceImportData-fileUpload:{}", JSONObject.toJSONString(fileUpload));
//            log.info(uuid + " deviceImportData-errors:{}", JSONObject.toJSONString(errors));
//        } catch (Exception e) {
//            log.error(uuid + " deviceImportData-error:{}", e);
//        }

        List<Map<String, Object>> jsonList = new ArrayList<>();

        log.info(uuid + " deviceImportData-errors:{}", JSONObject.toJSONString(errors));
        try {
            if (!CollectionUtil.isEmpty(errors)) {
                if (errors.size() < number){
                    fileUpload.setUploadStatus("part_success");
                }else {
                    fileUpload.setUploadStatus("fail");
                }
                errorMap.forEach((integer, s) ->{
                    Map<String, Object> res = new HashMap<>();
                    res.put("number",integer);
                    res.put("reason",s);
                    jsonList.add(res);
                });
                jsonList.sort((o1, o2) -> {
                    return Integer.parseInt(o1.get("number")+"")-Integer.parseInt(o2.get("number")+"");
                });
                fileUpload.setJsonInfo(JSONObject.toJSONString(jsonList));
                fileUploadMapper.updateById(fileUpload);
                log.info(uuid + " deviceImportData-fileUploadMapper:{}", JSONObject.toJSONString(errors));
            }else {
                fileUpload.setUploadStatus("success");
                fileUpload.setJsonInfo(JSONObject.toJSONString(jsonList));
                fileUploadMapper.updateById(fileUpload);
            }
        } catch (Exception e) {
            log.info(uuid + " insert-error:{}",e);
        }


        if (!CollectionUtil.isEmpty(sumDtus)) {
            log.info(uuid + " dtus:{}",JSONObject.toJSON(sumDtus));
            equipmentDelete(sumDtus, spId);
        }

        //企业级操作日志
        Integer resultCode = 1;
        if(!CollectionUtil.isEmpty(sumDtus)){
            if(!CollectionUtils.isEmpty(errors)){
                resultCode = OPERATE_RESULT_SUCCESS_PART;
            }
        }else {
            resultCode = OPERATE_RESULT_FAIL;
        }

        //操作日志log-25
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_43.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(dtu.name());
        operationLogService.insertLog(logVO);

        return resultCode;
    }

    public void equipmentDelete(List<String> ids, String spId) {
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Dtu::getIMEI, ids).eq(Dtu::getSpId, spId).eq(Dtu::getIsDeleted, 0);
        List<Dtu> dtus = dtuMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(dtus)) {
            return;
        }
        List<String> deviceCodeList = new ArrayList<>();
        List<String> imeiList = new ArrayList<>();
        for (Dtu dtu : dtus) {
            deviceCodeList.add(dtu.getDeviceCode());
            if (dtu.getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                imeiList.add(dtu.getIMEI());
            }
        }
        log.info("equipmentDelete-ids:{}", JSONObject.toJSONString(deviceCodeList));
        if (!CollectionUtil.isEmpty(deviceCodeList)) {
            //删除aep
            List<Map<String, String>> list = dtuAepMapper.selectDeviceIds(deviceCodeList);
            log.info("equipmentDelete-list:{}", JSONObject.toJSONString(list));
            if (!CollectionUtil.isEmpty(list)) {
                log.info("equipmentDelete-remove start");
                for (Map<String, String> s : list) {
                    String deviceId = s.get("device_id");
                    String deviceCode = s.get("deviceCode");
                    if (StringUtils.isEmpty(deviceId)) continue;
                    int deviceType= "NB".equals(s.get("communicationMode"))?0:1;
                    int header = Constants.UNICOM_EQUIPMENT_DEVICETYPE;
                    if (deviceType == Constants.CAT_EQUIPMENT_DEVICETYPE) header = 1;
                    if (s.get("protocol_version") == null || s.get("protocol_version").equals("v1.0")) {
                        header = Constants.TELECOM_EQUIPMENT_DEVICETYPE;
                    }else {
                        if (deviceType == 0) {
                            if (2 == Integer.parseInt(s.get("operators"))) header = Constants.MOVE_EQUIPMENT_DEVICETYPE;
                            if (3 == Integer.parseInt(s.get("operators")))
                                header = Constants.TELECOM_EQUIPMENT_DEVICETYPE;
                        }
                    }
                    Map<String, Object> res = equipmentCmpService.cmpRequest(new HashMap<>(), 2,
                            equipmentCmpService.getHeaders(header), deviceCode);
                    log.info("aepRegister——res,响应结果：{}",
                            JSONObject.toJSONString(res));

                    deleteDtuAep(deviceId);
                }
            }
            dtuMapper.updateByIds(deviceCodeList);
            if (!CollectionUtil.isEmpty(imeiList)) {
                dtuMapper.updateByImei(imeiList);
            }
            Map<String, List<Dtu>> collect = dtus.stream()
                    .collect(Collectors.groupingBy(Dtu::getEquipmentType, Collectors.toList()));
            collect.forEach((s, ds) -> {
                if (s.equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
                    ds.forEach(dtu -> {
                        deviceStateMapper.updateByImei(dtu.getIMEI(), dtu.getSpId());
                    });
                } else {
                    ds.forEach(dtu -> {
                        DeviceState deviceState = new DeviceState();
                        deviceState.setDeviceId(dtu.getIMEI());
                        deviceState.setDetectorCount(0);
                        deviceState.setMainBatteryValue(0);
                        deviceState.setDeviceStatus(0);
                        deviceState.setDeviceStatusInfo("");
                        UpdateWrapper<DeviceState> wrapper = new UpdateWrapper<>();
                        wrapper.lambda().or().eq(DeviceState::getDeviceId, dtu.getIMEI());
                        deviceStateMapper.update(deviceState, wrapper);
                    });
                }

            });
        }
    }


    public String setDetection(List<String> query, List<Map<String, String>> customerCode, String detectionType) {
        String res = "";
        if (!StringUtils.isEmpty(detectionType) && detectionType.contains(split)) {
            String stringValue = "";
            String[] split = detectionType.split(EquipmentServiceImpl.split);
            for (String s : split) {
                stringValue = stringValue + getStringValue(customerCode,
                        s, query.get(4), "value", "alias") + "、";
            }
            if (stringValue.length() > 0) {
                res = stringValue.substring(
                        0, stringValue.length() - 1);
            }
        } else {
            res = getStringValue(customerCode,
                    detectionType, query.get(4), "value", "alias");
        }
        return res;
    }

    public List<String> getQueryParams() {
        List<String> query = new ArrayList<>();
        query.add("Equipment_manufacturer");
        query.add("Equipment_type");
        query.add("Operator");
        query.add("Communication_mode");
        query.add("Detection_type");
        query.add("industry_type");
        return query;
    }


    /**
     * 数据导入
     *
     * @param file
     */
    @Override
    public String importData(MultipartFile file) {
        String spId = ApplicationUtils.getWorkingSpId();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        String uuid = IdUtil.fastSimpleUUID();
        log.info(uuid + " importData-timeStart:{}",System.currentTimeMillis());
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0); //指定输入流和sheet
        List<List<Object>> read = reader.read(1, reader.getRowCount());
        String username = ApplicationUtils.getWorkingUser().getUsername();
        String name = ApplicationUtils.getWorkingUser().getName();
        FileUpload fileUpload = new FileUpload();
        fileUpload = new FileUpload();
        fileUpload.setFileName(file.getOriginalFilename());
        fileUpload.setRowCount(read.size());
        fileUpload.setUploadTime(new Date());
        fileUpload.setUploadCreator(username);
        fileUpload.setCreatorName(name);
        fileUpload.setUploadCode("UPLOAD0001");
        fileUpload.setSpId(spId);
        fileUpload.setUploadStatus("waiting");
        //上传文件路径
        String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
        log.info(uuid + " importData-url:{}",JSONObject.toJSONString(url));
        fileUpload.setUploadUrl(url);
        fileUploadMapper.insert(fileUpload);
        log.info(uuid + " importData-fileUpload:{}",JSONObject.toJSONString(fileUpload));
        Integer id = fileUpload.getId();
        // 从主线程获取用户数据 放到局部变量中
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        SecurityContext context = SecurityContextHolder.getContext();
        executor.submit(() -> {
            try {
                // 把旧RequestAttributes放到新线程的RequestContextHolder中
                RequestContextHolder.setRequestAttributes(attributes);
                SecurityContextHolder.setContext(context);
                importDtu(file, spId, read, username, name, id, uuid);
                log.info(uuid + " importData-timeEnd:{}",System.currentTimeMillis());
            } catch (Exception e) {
                log.error(uuid + " importData-error:{}",e);
                FileUpload fileUpload1 = fileUploadMapper.selectById(id);
                if (fileUpload1 != null) {
                    fileUpload1.setUploadStatus("fail");
                    fileUploadMapper.updateById(fileUpload1);
                }

            }
        });
        LogVO vo = new LogVO();
        vo.setResultCode(Constants.OPERATE_RESULT_SUCCESS);
        LogRecordAspect.threadLocal.set(vo);
        log.info(uuid + " importData-return: {}", System.currentTimeMillis());
        return "";
    }

    public Integer importDtu(MultipartFile file, String spId, List<List<Object>> read,String username,String name,Integer id, String uuid) {
        log.info(uuid + " importDtu-start......");
        List<String> query = getQueryParams();
        List<Map<String, String>> customerCode = dictMap(null, query, null);
        List<Integer> errors = new ArrayList<>();
        Map<Integer, String> errorMap = new HashMap<>();
        log.info(uuid + " importData-data:{}", JSONObject.toJSONString(read));
        List<Dtu> sumDtus = new ArrayList<>();
        List<Dtu> dtus = new ArrayList<>();
        List<Dtu> updateDtus = new ArrayList<>();
        List<Dtu> allDtus = new ArrayList<>();
        Map<String, String> cmps = new HashMap<>();
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        Map<String,String> supplierMap = new HashMap<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
            supplierMap = supplierListVos.stream().collect(Collectors.toMap(AlarmSupplierListVo::getMsName,AlarmSupplierListVo::getAlarmSystemCode));
        }
        for (int i = 0; i < read.size(); i++) {
           Integer errorSize= errorMap.size();
            List<Object> objects = read.get(i);

            Dtu dtu = new Dtu();
            String loopPoint = "";
            for (int j = 0; j < objects.size(); j++) {
                if (objects.size() > 10 && j > 9) {
                    //拼回路
                    if (!StringUtils.isEmpty(objects.get(j)))
                        loopPoint = loopPoint + objects.get(j) + ";";
                }
            }
            dtu.setLoopPoint(loopPoint);
            try {
                dtu.setIMEI((objects.get(0) + "").trim());//设备号
                dtu.setParentImei((objects.get(0) + "").trim());
                dtu.setId((objects.get(0) + "").trim());
                dtu.setIccid((objects.get(1) + "").trim());
                String msCode = ObjectUtils.isEmpty(objects.get(2))?"":supplierMap.get((objects.get(2) + "").trim());
                dtu.setEquipmentManufacturer(msCode);//设备厂商
                dtu.setEquipmentType(getStringValue(customerCode, (objects.get(3) + "").trim(), query.get(1), "alias", "value"));//设备类型
                dtu.setEquipmentModel((objects.get(4) + "").trim());//设备型号
                dtu.setProtocolVersion((objects.get(5) + "").trim());//协议版本
                dtu.setDetectionType(getStringValue(customerCode, (objects.get(6) + "").trim(), query.get(4), "alias", "value"));//检测类型
                dtu.setOperators(getStringValue(customerCode, (objects.get(7) + "").trim(), query.get(2), "alias", "value"));//运营商
                dtu.setCommunicationMode(getStringValue(customerCode, (objects.get(8) + "").trim(), query.get(3), "alias", "value"));//通讯方式
            } catch (Exception e) {
                errors.add(i + 2);
                errorMap.put(i + 2,"必填项缺失");
                log.info(uuid + " 必填项缺失"+i + 2+":{}",e);
            }
            dtu.setSpId(spId);
            dtu.setInstallTime(new Date());
            dtu.setConsumerId(0);
            dtu.setSectorType(Constants.BLANK);
            dtu.setIsDeleted(0);
            String path = dtuMapper.selectPath(spId);
            if (!StringUtils.isEmpty(path)) dtu.setPath(path);
            Date date = new Date();
            dtu.setNetInTime(DateUtil.format(date, format));
            dtu.setRegisterTime(DateUtil.format(date, format));
            dtu.setCmpRegistered(1);
            if (objects.size() >= 10) {
                Object o = objects.get(9);
                dtu.setValidity(Integer.parseInt(StringUtils.isEmpty(o)||!NumberUtil.isNumber(o + "")
                        ? "0" : objects.get(9) + ""));//设备有效期
                if (!EquipmentType.GAS_ALARM_CONTROLLER.getCode().equals(dtu.getEquipmentType())) {
                    if (EquipmentType.HOME_GAS_DETECTOR.getCode()
                            .equals(dtu.getEquipmentType())) {
                        dtu.setValidity(5);
                    } else {
                        dtu.setValidity(3);
                    }
                }
                dtu.setExpirationTime("");
            }
            //进行校验
            String res = checkData(dtu, customerCode, query,errorMap,i+2);
            log.info(uuid + " importData-res:{}",res);
            sumDtus.add(dtu);
            if (res.equals("1")) {
                errors.add(i + 2);
                log.info(uuid + " importData-errors:{}",errors);
            } else if (!StringUtils.isEmpty(res) && res.length() > 2) {
                boolean  result=true;
                for (Dtu d : updateDtus) {
                    if (d.getIMEI().equals(res)){
                        result=false;
                        errors.add(i + 2);
                        errorMap.put(i + 2,res+"在excel重复");
                        log.info(uuid + " updateDtus:{}",res+"在excel重复");
                    }
                }
                for (Dtu d : dtus) {
                    if (d.getIMEI().equals(res)){
                        result=false;
                        errors.add(i + 2);
                        errorMap.put(i + 2,res+"在excel重复");
                        log.info(uuid + " dtus:{}",res+"在excel重复");
                    }
                }
                if (result){
                    dtu.setId(res);
                    updateDtus.add(dtu);
                }
            }
            log.info(uuid + " importData-size:{}:{}",errorSize,errorMap.size());
            if (errorMap.size()<=errorSize) {
                log.info(uuid + " importData-errorMap:{}",JSONObject.toJSON(errorMap));
                Map<String, Object> equipmentId = getEquipmentId(dtu.getEquipmentManufacturer()
                        , dtu.getOperators(), dtu.getEquipmentType(), allDtus, dtu.getIMEI());
                dtu.setSerialNumber(equipmentId.get("serialNumber") + "");
                dtu.setCreateYM(Integer.parseInt(DateUtil.format(new Date(), yyMM)));
                dtu.setDetectionType(StringUtils.isEmpty(dtu.getDetectionType()) ?
                        dtu.getDetectionType() : dtu.getDetectionType() + ";");
                dtu.setDeviceCode(equipmentId.get("id") + "");
                try {
                    log.info(uuid + " importData-cmpRegisterUpdate:{}",dtu.getIMEI());
                    allDtus.add(dtu);
                    cmpRegisterUpdate(dtu, 0, "NB".equals(dtu.getCommunicationMode())?0:1);
                    cmps.put(dtu.getDeviceCode(), dtu.getOperators());
                    if (res.equals("0")) {
                        dtus.add(dtu);
                    }
                } catch (Exception e) {
                    log.error(uuid + " importData-error:{}",e);
                    errors.add(i + 2);
                    errorMap.put(i + 2,e.getMessage());
                    continue;
                }
            }
        }
        allDtus.clear();

        log.info(uuid + " importData-errorMap",JSONObject.toJSONString(errorMap));
        FileUpload fileUpload = fileUploadMapper.selectById(id);
        try {
            //fileUpload = new FileUpload();
            fileUpload.setFileName(file.getOriginalFilename());
            fileUpload.setRowCount(read.size());
            fileUpload.setUploadTime(new Date());
//            fileUpload.setUploadCreator(username);
//            fileUpload.setCreatorName(name);
//            fileUpload.setUploadCode("UPLOAD0001");
//            fileUpload.setSpId(spId);
            fileUpload.setId(id);
            log.info(uuid + " importData-fileUpload",JSONObject.toJSONString(fileUpload));
            //上传文件路径
//            String url = fileUtil.uploadFile(file.getOriginalFilename(), file);
//            log.info(uuid + " importData-url",JSONObject.toJSONString(url));
//            fileUpload.setUploadUrl(url);
//            log.info(uuid + " importData-fileUpload:{}", JSONObject.toJSONString(fileUpload));
            log.info(uuid + " importData-errors:{}", JSONObject.toJSONString(errors));
        } catch (Exception e) {
            log.error(uuid + " fileUpload-error:{}", e);
        }

        List<Map<String, Object>> jsonList = new ArrayList<>();

        log.info(uuid + " importData-errors:{}", JSONObject.toJSONString(errors));
        try {
            if (!CollectionUtil.isEmpty(errors)) {
                if (errors.size()<read.size()){
                    fileUpload.setUploadStatus("part_success");
                }else {
                    fileUpload.setUploadStatus("fail");
                }
                errorMap.forEach((integer, s) ->{
                    Map<String, Object> res = new HashMap<>();
                    res.put("number",integer);
                    res.put("reason",s);
                    jsonList.add(res);
                });
                jsonList.sort((o1, o2) -> {
                    return Integer.parseInt(o1.get("number")+"")-Integer.parseInt(o2.get("number")+"");
                });
                fileUpload.setJsonInfo(JSONObject.toJSONString(jsonList));
                fileUploadMapper.updateById(fileUpload);
                log.info(uuid + " importData-fileUploadMapper:{}", JSONObject.toJSONString(errors));
            }else {
                fileUpload.setUploadStatus("success");
                fileUpload.setJsonInfo(JSONObject.toJSONString(jsonList));
                fileUploadMapper.updateById(fileUpload);
            }
        } catch (Exception e) {
            log.info(uuid + " insert-error:{}",e);
        }


        if (!CollectionUtil.isEmpty(dtus)) {
            log.info(uuid + " dtus:{}",JSONObject.toJSON(dtus));
            dtuMapper.insertBatch(dtus);
        }
        if (!CollectionUtil.isEmpty(updateDtus)) {
            log.info(uuid + " updateDtus:{}",JSONObject.toJSON(updateDtus));
            for (Dtu dtu : updateDtus) {
                UpdateWrapper<Dtu> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().eq(Dtu::getIMEI, dtu.getIMEI());
                dtuMapper.update(dtu, updateWrapper);
            }
        }

        //企业级操作日志
        Integer resultCode = 1;
        if(!CollectionUtil.isEmpty(dtus) || !CollectionUtil.isEmpty(updateDtus)){
            if(!CollectionUtils.isEmpty(errors)){
                resultCode = OPERATE_RESULT_SUCCESS_PART;
            }
        }else {
            resultCode = OPERATE_RESULT_FAIL;
        }

        //操作日志log-25
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_25.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(dtu.name());
        operationLogService.insertLog(logVO);

        return resultCode;
    }

    public String getStringValue(List<Map<String, String>> customerCode, Object obj
            , String filter, String keys1, String keys2) {
        //分组过滤
        String value = null;
        try {
            List<Map<String, String>> maps = customerCode.stream().filter(stringStringMap -> {
                return stringStringMap.get("dict_code").equals(filter);
            }).collect(Collectors.toList());
            log.info("getStringValue-字典值{}", JSONObject.toJSONString(maps));
            value = "";
            for (Map<String, String> map : maps) {
                if (map.get(keys1).equals(obj)) {
                    value = map.get(keys2);
                    return value;
                }
            }
        } catch (Exception e) {
            log.error("getStringValue-error:{}", e);
        }
        return value;
    }

    @Override
    public List<Dtu> getWithType2(LatestLogListRequest request) {
        return dtuMapper.getQueryList(request.getImei(), request.getEquipmentName(),
                request.getEquipmentTypes(), request.getSpId(), request.getImeiList(),
                request.getMemberId(), request.getIndustryType(), request.getContactName(),
                request.getContactPhone(), request.getInstallationAddress(),
                request.getEquipmentModel(), request.getEquipmentManufacturer());
    }

    @Override
    public List<Dtu> listEquipmentWithType2(LatestLogListRequest request) {
        return dtuMapper.listEquipmentWithType2(request.getImei(), request.getEquipmentName(),
                request.getEquipmentTypes(), request.getSpId(), request.getImeiList(),
                request.getMemberId(), request.getIndustryType(), request.getContactName(),
                request.getContactPhone(), request.getInstallationAddress(),
                request.getEquipmentModel(), request.getEquipmentManufacturer(), request.getOrgCode(), request.getCustomerAddress());
    }

    @Override
    public void editPosition(EquipmentPositionRequest request) {
        String spId = StringUtils.isEmpty(request.getSpId())?ApplicationUtils.getWorkingSpId():request.getSpId();
        //短信运营商禁用字符校验
        if (StringUtil.isNotEmpty(request.getInstallationPosition())) {
            if (request.getInstallationPosition().contains(Constants.SMS_DISABLE_STR1) ||
                    request.getInstallationPosition().contains(Constants.SMS_DISABLE_STR2)) {
                throw new BizException("安装位置包含字符【】,保存失败");
            }
        }

        Dtu dtu = new Dtu();
        dtu.setInstallationPosition(request.getInstallationPosition());
        //更新设备位置
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Dtu::getSpId, spId);
        List<Dtu> dtus = dtuMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(dtus)) {
            throw new BizException("未查询到该设备" + request.getImei());
        }
        QueryWrapper<Consumer> queryOldWrapper = new QueryWrapper<>();
        queryOldWrapper.lambda().eq(Consumer::getId, dtus.get(0).getConsumerId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumerOld = consumerService.getOne(queryOldWrapper);
        if (consumerOld!=null)workOrderHistoryService.existWorkOrder(consumerOld.getSubsCode(),spId);
        if (consumerOld!=null&&consumerOld.getStatus()==1)  throw new BizException("工单进行中，客户信息不可修改");
        int update = dtuMapper.update(dtu, queryWrapper);
        if (update == 0) {
            throw new BizException("未查询到该设备被编辑:" + request.getImei());
        }

        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setConsumerId(dtus.get(0).getConsumerId().toString());
        vo.setDetail(LogUtil.compareEntity(dtuMapper.selectById(dtus.get(0).getId()), dtus.get(0), Dtu.class));
        LogRecordAspect.threadLocal.set(vo);


        //操作日志log-21
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_21.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.consumer.name());
        logVO.setTableKey(request.getImei());
        logVO.setOperationBefore(dtus.get(0).getInstallationPosition());
        logVO.setOperationAfter(request.getInstallationPosition());
        if (request.getTemplateType() != null) {
            if (request.getTemplateType() == BIND_CHANNEL_ASST) {
                logVO.setOperationPersonName("时刻助手销售单");
                logVO.setOperationPersonCode("asst");
            }
        }
        operationLogService.insertLog(logVO);
    }


    @Override
    public void editEquipmentName(EquipmentPositionRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();

        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Dtu::getIMEI, request.getImei()).eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE);
        Dtu oldDtu = this.getOne(queryWrapper);
        LambdaQueryWrapper<Consumer> query = new LambdaQueryWrapper<>();
        query.or().eq(Consumer::getIsDeleted,0).eq(Consumer::getId,oldDtu.getConsumerId());
        List<Consumer> consumers = consumerMapper.selectList(query);
       if (!CollectionUtils.isEmpty(consumers))workOrderHistoryService.existWorkOrder(consumers.get(0).getSubsCode(),spId);
        Dtu dtu = new Dtu();
        BeanUtils.copyProperties(oldDtu, dtu);
        dtu.setName(request.getName());
        dtu.setInstallDate(request.getInstallDate());
        this.updateById(dtu);

        //企业级操作日志
        LogVO vo = new LogVO();
        vo.setConsumerId(oldDtu.getConsumerId().toString());
        vo.setDetail(LogUtil.compareEntity(dtu, oldDtu, Dtu.class));
        LogRecordAspect.threadLocal.set(vo);

        //操作日志log-22
        OperationLogVO logVO = new OperationLogVO();
        List<Integer> logCodeList = new ArrayList<>();
        logCodeList.add(OperationTypeEnum.OPERATION_TYPE_22.getCode());
        logVO.setCodeList(logCodeList);
        logVO.setTableName(TableConst.dtu.name());
        logVO.setTableKey(request.getImei());
        operationLogService.insertLog(logVO);
    }

    @Override
    public void dictMapOpt(@Valid Dictionary dictionary) {
        if (dictionary.getId() != null) {
            dictionaryMapper.updateById(dictionary);
        } else {
            dictionaryMapper.insert(dictionary);
        }
    }


    @Override
    public List<Map<String, String>> dictMap(String type, List<String> types, String spId) {
        List<Map<String, String>> maps = null;
        if ("industry_type".equals(type) && CollectionUtil.isEmpty(types)) {
            Integer configurable = dictionaryMapper.selectConfigurable(spId);
            if (configurable != null && configurable == 0) {
                spId = "0";
            }
        }
        try {
            maps = dictionaryMapper.selectKeyValue(type, types, spId);
        } catch (Exception e) {
            log.error("dictMap-error:{}", e);
        }
        if (CollectionUtil.isEmpty(maps)) throw new BizException("未查询到客户相关字典数据,请联系管理员");
        List<Map<String, String>> resList = new ArrayList<>();
        if (!CollectionUtil.isEmpty(maps)) {
            Set<String> strings = new HashSet<>();
            maps.forEach(stringStringMap -> {
                if (!strings.contains(stringStringMap.get("alias"))) {
                    strings.add(stringStringMap.get("alias"));
                    resList.add(stringStringMap);
                }
            });

        }
        return resList;
    }

    public String checkData(Dtu dtu, List<Map<String, String>> customerCode, List<String> querys
            ,Map<Integer,String> errorMap,Integer lineNumber) {
        String result = "0";
        //协议版本
        String protocolVersion = dtu.getProtocolVersion();
        if (StringUtils.isEmpty(protocolVersion) || (!protocolVersion.equals("v1.0") &&!protocolVersion.equals("v2.0"))) {
            result = "1";
            log.info("checkData-reason协议版本问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"协议版本存在问题");
            return result;
        }
        //设备号
        String imei = dtu.getIMEI();
        if (StringUtils.isEmpty(imei) || imei.length() < 15 || imei.length() > 17) {
            result = "1";
            log.info("checkData-reason设备号问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"设备IMEI存在问题");
            return result;
        }
        //设备厂商
        if ( StringUtils.isEmpty(dtu.getEquipmentManufacturer()) ) {
            result = "1";
            log.info("checkData-reason设备厂商问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"设备厂商存在问题");
            return result;
        }
        //设备类型
        if (StringUtils.isEmpty(dtu.getEquipmentType())
                || !dealDictData(customerCode, querys.get(1), "value")
                .contains(dtu.getEquipmentType()) || dtu.getEquipmentType().equals("Point_type_gas_detector")) {
            result = "1";
            log.info("checkData-reason设备类型问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"设备类型存在问题");
            return result;
        }
        //设备型号
        if (StringUtils.isEmpty(dtu.getEquipmentModel())) {
            result = "1";
            log.info("checkData-reason设备型号问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"设备型号存在问题");
            return result;
        }
        //检测类型:一氧化碳、甲烷
        if (!StringUtils.isEmpty(dtu.getDetectionType())
                && !dealDictData(customerCode, querys.get(4), "value")
                .contains(dtu.getDetectionType())) {
            result = "1";
            log.info("checkData-reason一氧化碳、甲烷问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"检测类型存在问题");
            return result;
        }
        //运营商:电信、联通、移动
        if (!StringUtils.isEmpty(dtu.getOperators())
                && !dealDictData(customerCode, querys.get(2), "value")
                .contains(dtu.getOperators()) || StringUtils.isEmpty(dtu.getOperators())) {
            result = "1";
            log.info("checkData-reason运营商问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"运营商存在问题");
            return result;
        }

        //通讯方式:NB、4G
        if (!StringUtils.isEmpty(dtu.getCommunicationMode())
                && !dealDictData(customerCode, querys.get(3), "value")
                .contains(dtu.getCommunicationMode())
                || StringUtils.isEmpty(dtu.getCommunicationMode())) {
            result = "1";
            log.info("checkData-reason通讯方式问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"通讯方式存在问题");
            return result;
        }
        //设备有效期:仅可填写数字
        if (!StringUtils.isEmpty(dtu.getValidity())
                && !NumberUtil.isNumber(dtu.getValidity() + "")) {
            result = "1";
            log.info("checkData-reason设备有效期问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"设备有效期存在问题");
            return result;
        }


        List<Dtu> dtus = checkIMEI(imei);
        if (!CollectionUtil.isEmpty(dtus) && dtus.get(0).getIsDeleted() == 1) {
            return dtus.get(0).getId();
        } else if (!CollectionUtil.isEmpty(dtus) && dtus.get(0).getIsDeleted() == 0) {
            result = "1";
            log.info("checkData-reason imei问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"imei已被注册");
            return result;
        }
        List<Dtu> ds = checkICCID(dtu.getIccid());
        if (!CollectionUtil.isEmpty(ds)) {
            result = "1";
            log.info("checkData-reason iccid问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"iccid存在问题");
        }

        return result;
    }

    public String checkDeviceDelete(String imei, String spId, Map<Integer,String> errorMap,Integer lineNumber) {
        String result = "0";
        if (StringUtils.isEmpty(imei) || imei.length() < 15 || imei.length() > 17) {
            result = "1";
            log.info("checkData-reason设备号问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"删除失败：设备IMEI号有误");
            return result;
        }
        List<Dtu> dtus = checkIMEI(imei);
        if (CollectionUtil.isEmpty(dtus) || dtus.get(0).getIsDeleted() == 1) {
            result = "1";
            log.info("checkData-reason imei问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"删除失败：未找到该设备");
            return result;
        }

        if (dtus.get(0).getConsumerId() > 0) {
            result = "1";
            log.info("checkData-reason imei问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"删除失败：设备已与客户绑定");
            return result;
        }

        if (!spId.equals(dtus.get(0).getSpId())) {
            result = "1";
            log.info("checkData-reason imei问题:{}", JSONObject.toJSONString(dtu));
            errorMap.put(lineNumber,"删除失败：设备不在当前组织");
            return result;
        }

        if (DeviceConstant.WiFi_COMMUNICATIONMODE
                .equals(dtus.get(0).getCommunicationMode())) {
            throw new BizException("删除失败：暂不支持删除通讯方式为WiFi的设备");
        }

        return result;
    }

    private Map<String, Object> getEquipmentId(String equipmentManufacturer,
                                               String operators, String equipmentType,
                                               List<Dtu> dtus,String imei) {
        Map<String, Object> result = new HashMap<>();
        int ym = Integer.parseInt(DateUtil.format(new Date(), yyMM));
        Integer integer = dtuMapper.selectMaxNumber(ym);
        String serialNumber = integer == null ? "00001" :
                String.valueOf( integer+ 1);

        if (!CollectionUtil.isEmpty(dtus)) {
            dtus.sort((o1, o2) -> {
                return -Integer.parseInt(o1.getSerialNumber()) + Integer.parseInt(o2.getSerialNumber());
            });
            String number = String.valueOf(Integer.parseInt(dtus.get(0).getSerialNumber()) + 1);
            serialNumber = Integer.parseInt(number) > Integer.parseInt(serialNumber) ? number : serialNumber;

        }
        int length = serialNumber.length();
        //流水号补位法
        if (length < 5) {
            for (int i = 0; i < (5 - length); i++) {
                serialNumber = "0" + serialNumber;
            }
        }
        //获取当前使用流水号
        String constant = imei.substring(imei.length()-4, imei.length());
        if (StringUtils.isEmpty(operators)) constant = imei.substring(imei.length()-3, imei.length());
        Integer value = (operators + equipmentManufacturer + constant + ym + serialNumber).length() - 16;
        if (value > 0 && value < constant.length()) {
            constant = constant.substring(value, constant.length());
        }
        String id = operators + equipmentManufacturer + constant + ym + serialNumber;
        result.put("id", id);
        result.put("serialNumber", serialNumber);
        return result;
    }

    public static List<String> dealDictData(List<Map<String, String>> maps, String code, String keys) {
        List<String> result = new ArrayList<>();
        Map<String, List<Map<String, String>>> dictCodes = maps.stream()
                .collect(Collectors.groupingBy(map -> map.get("dict_code"), Collectors.toList()));
        List<Map<String, String>> res = dictCodes.get(code);
        res.forEach(map -> {
            result.add(map.get(keys));
        });
        return result;
    }


    public List<Dtu> checkIMEI(String imei) {
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(Dtu::getIMEI, imei);
        return dtuMapper.selectList(queryWrapper);
    }

    public List<Dtu> checkICCID(String iccid) {
        QueryWrapper<Dtu> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(Dtu::getIccid, iccid).eq(Dtu::getIsDeleted, 0);
        return dtuMapper.selectList(queryWrapper);
    }

    private void cmpRegisterUpdate(Dtu dtu, int optType, int deviceType) {
        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("deviceCode", dtu.getDeviceCode());
        jsonData.put("imei", dtu.getIMEI());
        if (deviceType != Constants.ZJ_EQUIPMENT_DEVICETYPE) jsonData.put("iccid", dtu.getIccid());

        jsonData.put("deviceType", deviceType);
        int header = Constants.UNICOM_EQUIPMENT_DEVICETYPE;
        if (deviceType == Constants.ZJ_EQUIPMENT_DEVICETYPE) header = 9;
        if (deviceType == Constants.CAT_EQUIPMENT_DEVICETYPE) header = 1;
        String protocolVersion = dtu.getProtocolVersion();
        if( "v1.0".equals(protocolVersion) ){// "1.0"的设备都走电信平台
            header = Constants.TELECOM_EQUIPMENT_DEVICETYPE;
        }else {
            if (deviceType == 0) {
                if (2 == Integer.parseInt(dtu.getOperators())) header = Constants.MOVE_EQUIPMENT_DEVICETYPE;
                if (3 == Integer.parseInt(dtu.getOperators())) header = Constants.TELECOM_EQUIPMENT_DEVICETYPE;
            }
        }
        Map<String, Object> res = equipmentCmpService.cmpRequest(jsonData, optType,
                equipmentCmpService.getHeaders(header), dtu.getDeviceCode());
        log.info("cmpRegisterUpdate——res,响应结果：{}",
                JSONObject.toJSONString(res));
        if ((boolean) res.get("result")) {
            if (optType == 1) return;
            List<DtuAep> dtuAepList = checkDtuAep(dtu.getIMEI(), dtu.getSpId());
            if (CollectionUtils.isEmpty(dtuAepList)) {
                DtuAep dtuAep = new DtuAep();
                dtuAep.setDeviceId(dtu.getDeviceCode());
                dtuAep.setIMEI(dtu.getIMEI());
                dtuAep.setRegisterStatus(1);
                dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                dtuAep.setSpId(dtu.getSpId());
                dtuAepMapper.insert(dtuAep);
            } else {
                for (DtuAep dtuAep : dtuAepList) {
                    dtuAep.setDeviceId(dtu.getDeviceCode());
                    dtuAep.setIMEI(dtu.getIMEI());
                    dtuAep.setRegisterStatus(1);
                    dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    dtuAep.setSpId(dtu.getSpId());
                    dtuAepMapper.updateById(dtuAep);
                }
            }
        } else {
            if ("1013".equals(res.get("code")) || "1012".equals(res.get("code"))) {
                // 已经注册过了，这里直接新增成功，但是deviceID需要注册过的
                // 查询注册过的信息
                jsonData = new HashMap<>();
                jsonData.put("imei", dtu.getIMEI());
                JSONObject result = equipmentCmpService.query(jsonData, equipmentCmpService.getHeaders(header));
                if (result.get("deviceCode") != null && !StringUtils.isEmpty(result.getString("deviceCode"))) {
                    List<DtuAep> dtuAepList = checkDtuAep(dtu.getIMEI(), dtu.getSpId());
                    if (CollectionUtils.isEmpty(dtuAepList)) {
                        DtuAep dtuAep = new DtuAep();
                        dtuAep.setDeviceId(result.getString("deviceCode"));
                        dtuAep.setIMEI(dtu.getIMEI());
                        dtuAep.setRegisterStatus(1);
                        dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        dtuAep.setSpId(dtu.getSpId());
                        dtuAepMapper.insert(dtuAep);
                    } else {
                        for (DtuAep dtuAep : dtuAepList) {
                            dtuAep.setDeviceId(result.getString("deviceCode"));
                            dtuAep.setIMEI(dtu.getIMEI());
                            dtuAep.setRegisterStatus(1);
                            dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                            dtuAep.setSpId(dtu.getSpId());
                            dtuAepMapper.updateById(dtuAep);
                        }
                    }
                } else {
                    if (result.get("msg") == null || StringUtils.isEmpty(result.getString("msg"))) {
                        throw new BizException("注册失败：IMEI号" + dtu.getIMEI() + "已被其他租户注册");
                    }
                    else {
                        throw new BizException("注册失败：" + result.get("msg"));
                    }
                }
            } else if ("1008".equals(res.get("code"))) {
                throw new BizException("注册失败：" + "设备IMEI号不存在");
            } else if ("1011".equals(res.get("code"))) {
                throw new BizException("注册失败：" + "设备号错误或非法");
            } else if ("1010".equals(res.get("code"))) {
                throw new BizException("注册失败：" + "设备ICCID号不存在");
            } else {
                throw new BizException("注册失败：" + res.get("msg"));
            }
        }
    }

    private void cmpRegisterUpdate(Dtu dtu, int optType) {
        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("deviceCode", dtu.getDeviceCode());
        jsonData.put("imei", dtu.getIMEI());
        jsonData.put("iccid", dtu.getIccid());

        jsonData.put("deviceType", 0);
        int header = Constants.UNICOM_EQUIPMENT_DEVICETYPE;
        if (2==Integer.parseInt(dtu.getOperators()) ) {
            header=Constants.MOVE_EQUIPMENT_DEVICETYPE;
        }else if (3==Integer.parseInt(dtu.getOperators()) ) {
            header=Constants.TELECOM_EQUIPMENT_DEVICETYPE;
        }
        Map<String, Object> res = equipmentCmpService.cmpRequest(jsonData, optType,
                equipmentCmpService.getHeaders(header), dtu.getDeviceCode());
        log.info("cmpRegisterUpdate——res,响应结果：{}",
                JSONObject.toJSONString(res));
        if ((boolean) res.get("result")) {
            if (optType == 1) return;
            List<DtuAep> dtuAepList = checkDtuAep(dtu.getIMEI(), dtu.getSpId());
            if (CollectionUtils.isEmpty(dtuAepList)) {
                DtuAep dtuAep = new DtuAep();
                dtuAep.setDeviceId(dtu.getDeviceCode());
                dtuAep.setIMEI(dtu.getIMEI());
                dtuAep.setRegisterStatus(1);
                dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                dtuAep.setSpId(dtu.getSpId());
                dtuAepMapper.insert(dtuAep);
            } else {
                for (DtuAep dtuAep : dtuAepList) {
                    dtuAep.setDeviceId(dtu.getDeviceCode());
                    dtuAep.setIMEI(dtu.getIMEI());
                    dtuAep.setRegisterStatus(1);
                    dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    dtuAep.setSpId(dtu.getSpId());
                    dtuAepMapper.updateById(dtuAep);
                }
            }
        } else {
            if ("1013".equals(res.get("code")) || "1012".equals(res.get("code"))) {
                // 已经注册过了，这里直接新增成功，但是deviceID需要注册过的
                // 查询注册过的信息
                jsonData = new HashMap<>();
                jsonData.put("imei", dtu.getIMEI());
                JSONObject result = equipmentCmpService.query(jsonData, equipmentCmpService.getHeaders(header));
                if (result.get("deviceCode") != null && !StringUtils.isEmpty(result.getString("deviceCode"))) {
                    List<DtuAep> dtuAepList = checkDtuAep(dtu.getIMEI(), dtu.getSpId());
                    if (CollectionUtils.isEmpty(dtuAepList)) {
                        DtuAep dtuAep = new DtuAep();
                        dtuAep.setDeviceId(result.getString("deviceCode"));
                        dtuAep.setIMEI(dtu.getIMEI());
                        dtuAep.setRegisterStatus(1);
                        dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                        dtuAep.setSpId(dtu.getSpId());
                        dtuAepMapper.insert(dtuAep);
                    } else {
                        for (DtuAep dtuAep : dtuAepList) {
                            dtuAep.setDeviceId(result.getString("deviceCode"));
                            dtuAep.setIMEI(dtu.getIMEI());
                            dtuAep.setRegisterStatus(1);
                            dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                            dtuAep.setSpId(dtu.getSpId());
                            dtuAepMapper.updateById(dtuAep);
                        }
                    }
                } else {
                    throw new BizException("注册失败：" + result.get("msg"));
                }
            } else if ("1008".equals(res.get("code"))) {
                throw new BizException("注册失败：" + "设备IMEI号不存在");
            } else if ("1011".equals(res.get("code"))) {
                throw new BizException("注册失败：" + "设备号错误或非法");
            } else if ("1010".equals(res.get("code"))) {
                throw new BizException("注册失败：" + "设备ICCID号不存在");
            } else {
                throw new BizException("注册失败：" + res.get("msg"));
            }
        }
    }

    public List<DtuAep> checkDtuAep(String imei, String spId) {
        QueryWrapper<DtuAep> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(DtuAep::getIMEI, imei).eq(DtuAep::getSpId, spId).eq(DtuAep::getIsDeleted, 0);
        return dtuAepMapper.selectList(queryWrapper);
    }


    private String aepRegister(Dtu dtu) {
        String deviceId = "";
        if (!"4G".equals(dtu.getCommunicationMode())) {
            Map<String, Object> params = new HashMap<>();
            params.put("imsi", "");
            params.put("deviceName", StringUtils.isEmpty(dtu.getIMEI()) ? "" : dtu.getIMEI());
            params.put("imei", dtu.getIMEI());
            Map<String, Object> res = equipmentAepService.aepRequest(params, 1);
            log.info("aepRegister——res,响应结果：{}",
                    JSONObject.toJSONString(res));
            if ((boolean) res.get("result")) {
                Object data = res.get("data");
                if (data != null) {
                    deviceId = insertAep(dtu, data);
                }
            } else {
                try {
                    params = new HashMap<>();
                    params.put("searchValue", dtu.getIMEI());
                    params.put("pageNow", 1);
                    params.put("pageSize", 1);
                    JSONObject map = equipmentAepService.query(params);
                    JSONArray data = map.getJSONArray("list");
                    if(CollectionUtil.isNotEmpty(data)) {
                        deviceId = insertAep(dtu, JSONObject.toJSONString(data.get(0)));
                    }else {
                        throw new BizException("注册失败：" + res.get("msg"));
                    }
                } catch (BizException e) {
                    throw new BizException("注册失败：" + res.get("msg"));
                }
            }
        } else {
            List<DtuAep> dtuAepList = checkDtuAep(dtu.getIMEI(), dtu.getSpId());
            if (CollectionUtils.isEmpty(dtuAepList)) {
                DtuAep dtuAep = new DtuAep();
                dtuAep.setDeviceId("");
                dtuAep.setIMEI(dtu.getIMEI());
                dtuAep.setRegisterStatus(1);
                dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                dtuAep.setSpId(dtu.getSpId());
                dtuAepMapper.insert(dtuAep);
            } else {
                for (DtuAep dtuAep : dtuAepList) {
                    dtuAep.setDeviceId("");
                    dtuAep.setIMEI(dtu.getIMEI());
                    dtuAep.setRegisterStatus(1);
                    dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                    dtuAep.setSpId(dtu.getSpId());
                    dtuAepMapper.updateById(dtuAep);
                }
            }
        }
        return deviceId;
    }

    private String insertAep(Dtu dtu, Object data) {
        JSONObject object = JSONObject.parseObject(data + "");
        String deviceId;
        deviceId = object.getString("deviceId");
        List<DtuAep> dtuAepList = checkDtuAep(dtu.getIMEI(), dtu.getSpId());
        if (CollectionUtils.isEmpty(dtuAepList)) {
            DtuAep dtuAep = new DtuAep();
            dtuAep.setDeviceId(deviceId);
            dtuAep.setIMEI(dtu.getIMEI());
            dtuAep.setRegisterStatus(1);
            dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            dtuAep.setSpId(dtu.getSpId());
            dtuAepMapper.insert(dtuAep);
        } else {
            for (DtuAep dtuAep : dtuAepList) {
                dtuAep.setDeviceId(deviceId);
                dtuAep.setIMEI(dtu.getIMEI());
                dtuAep.setRegisterStatus(1);
                dtuAep.setRegisterTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                dtuAep.setSpId(dtu.getSpId());
                dtuAepMapper.updateById(dtuAep);
            }
        }
        //idmap
        idmapService.deleteData(dtu.getIMEI());
        Idmap idmap = new Idmap();
        log.info("dtu.IMEI:{}", dtu.getIMEI());
        idmap.setImei(dtu.getIMEI());
        idmap.setDeviceId(object.getString("deviceId"));
        try {
            idmapService.saveData(idmap);
        } catch (Exception e) {
            log.error("idmapService.saveData-error:{}", e);
            throw new BizException("注册失败");
        }
        return deviceId;
    }


    private void aepRemove(String deviceId) {
        Map<String, Object> params = new HashMap<>();
        params.put("deviceId", deviceId);
        Map<String, Object> res = equipmentAepService.aepRequest(params, 2);
        log.info("aepRemove——res,响应结果：{}",
                JSONObject.toJSONString(res));
        if ((boolean) res.get("result")) {
            deleteDtuAep(deviceId);
        }
    }

    public List<Dtu> getEqumentsByConsumerId(String consumerId) {
        List<Dtu> dtus = dtuMapper.selectByConsumerId(consumerId);
        log.info("getEqumentsByConsumerId-dtus:{}", JSONObject.toJSONString(dtus));
        return dtus;
    }

    private void checkLoopPoint(String loopPoint) {
        if (!StringUtils.isEmpty(loopPoint) && loopPoint.contains(split)) {
            String[] split = loopPoint.split(EquipmentServiceImpl.split);
            if (split.length > 0) {
                for (String s : split) {
                    if (!NumberUtil.isNumber(s) || Integer.parseInt(s) < 0) {
                        throw new BizException("回路应为正整数");
                    }
                }
            }
        }
    }

    /**
     * 根据imei获取
     *
     * @param imei
     * @return
     */
    public Map<String, Object> selectByImei(String imei, String spId) {
        String IMEI = imei;
        Map<String, Object> callMap = dtuMapper.selectCallInfoByImei(IMEI, spId);
        if (callMap == null || callMap.isEmpty()) {
            log.error("selectByImei-error,设备号:{},spId:{}", IMEI, spId);
            return null;
        }
        return callMap;
    }

    @Override
    public String getEquipmentManufacturerName(String equipmentManufacturerCode,String spId) {
        try {
            if (StringUtils.isEmpty(equipmentManufacturerCode)) {
                return "";
            }
            //设备厂商名称
            ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", response);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
                supplierListVos = response.getData();
            }
            List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                    equipmentManufacturerCode)).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(listVos)) {
                return "";
            }
            return listVos.get(0).getMsName();
        }catch (Exception e){
            log.error("获取厂商报错",e);
        }
        return "";
    }
}
